c语言一个插入删除的循环链表
时间: 2024-05-06 14:16:45 浏览: 9
循环链表是一种特殊的链表,其尾节点指向头节点。在插入和删除元素时,需要注意节点的前驱和后继节点的指向。下面是一个基于C语言的插入和删除循环链表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义循环链表节点
typedef struct node {
int data;
struct node* next;
} Node;
// 初始化循环链表
void initList(Node** head) {
*head = (Node*)malloc(sizeof(Node));
(*head)->data = 0;
(*head)->next = *head;
}
// 插入节点
void insertNode(Node* head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = head;
Node* p = head;
while (p->next != head) {
p = p->next;
}
p->next = newNode;
}
// 删除节点
void deleteNode(Node* head, int value) {
Node* p = head->next;
Node* pre = head;
while (p != head) {
if (p->data == value) {
pre->next = p->next;
free(p);
return;
}
pre = p;
p = p->next;
}
}
// 输出循环链表
void printList(Node* head) {
Node* p = head->next;
while (p != head) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node* head;
initList(&head);
insertNode(head, 1);
insertNode(head, 2);
insertNode(head, 3);
insertNode(head, 4);
printList(head); // 输出:1 2 3 4
deleteNode(head, 3);
printList(head); // 输出:1 2 4
return 0;
}
```
在上面的代码中,我们首先定义了循环链表的节点结构体`Node`,其中包括节点的数据域`data`和指向下一个节点的指针`next`。然后定义了初始化循环链表的函数`initList`、插入节点的函数`insertNode`和删除节点的函数`deleteNode`。
在插入节点时,我们先创建一个新的节点,然后遍历循环链表找到尾节点,将其指向新节点。在删除节点时,我们先通过遍历找到要删除的节点,然后将其前驱节点的`next`指针指向其后继节点,并释放要删除的节点所占用的内存。
最后,我们通过调用`printList`函数来输出循环链表的所有节点的数据。