用c语言环形链表实现前插和尾插
时间: 2024-04-05 07:12:15 浏览: 70
环形链表是一种特殊的链表,其最后一个节点指向第一个节点,形成一个环。环形链表的插入操作和单向链表类似,只是在尾插时需要特殊处理最后一个节点的指针。以下是环形链表的前插和尾插实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义节点结构体
typedef struct Node {
int data;
struct Node *next;
} Node;
// 创建节点
Node *createNode(int data) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
return node;
}
// 前插节点
void insertFront(Node **head, int data) {
Node *node = createNode(data);
if (*head == NULL) {
*head = node;
node->next = node;
} else {
Node *last = *head;
while (last->next != *head) {
last = last->next;
}
node->next = *head;
last->next = node;
*head = node;
}
}
// 尾插节点
void insertEnd(Node **head, int data) {
Node *node = createNode(data);
if (*head == NULL) {
*head = node;
node->next = node;
} else {
Node *last = *head;
while (last->next != *head) {
last = last->next;
}
last->next = node;
node->next = *head;
}
}
// 打印链表
void printList(Node *head) {
if (head == NULL) {
printf("链表为空\n");
return;
}
Node *node = head;
do {
printf("%d ", node->data);
node = node->next;
} while (node != head);
printf("\n");
}
int main() {
Node *head = NULL;
// 前插测试
insertFront(&head, 3);
insertFront(&head, 2);
insertFront(&head, 1);
printf("前插后的链表:");
printList(head);
// 尾插测试
insertEnd(&head, 4);
insertEnd(&head, 5);
insertEnd(&head, 6);
printf("尾插后的链表:");
printList(head);
return 0;
}
```
输出结果为:
```
前插后的链表:1 2 3
尾插后的链表:1 2 3 4 5 6
```
阅读全文
相关推荐



