c语言双向循环链表基本操作,请用代码展示
时间: 2023-05-19 11:02:45 浏览: 116
C语言双向循环链表的基本操作
4星 · 用户满意度95%
以下是 C 语言双向循环链表的基本操作代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
struct Node* head = NULL;
// 在链表末尾插入节点
void insert(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
head->prev = head;
head->next = head;
} else {
struct Node* lastNode = head->prev;
lastNode->next = newNode;
newNode->prev = lastNode;
newNode->next = head;
head->prev = newNode;
}
}
// 在链表中删除节点
void delete(int data) {
if (head == NULL) {
printf("链表为空,无法删除节点!\n");
return;
}
struct Node* currentNode = head;
while (currentNode->data != data) {
currentNode = currentNode->next;
if (currentNode == head) {
printf("链表中没有该节点!\n");
return;
}
}
if (currentNode == head) {
head = head->next;
}
struct Node* prevNode = currentNode->prev;
struct Node* nextNode = currentNode->next;
prevNode->next = nextNode;
nextNode->prev = prevNode;
free(currentNode);
}
// 在链表中查找节点
void search(int data) {
if (head == NULL) {
printf("链表为空,无法查找节点!\n");
return;
}
struct Node* currentNode = head;
while (currentNode->data != data) {
currentNode = currentNode->next;
if (currentNode == head) {
printf("链表中没有该节点!\n");
return;
}
}
printf("链表中存在节点 %d\n", data);
}
// 打印链表中的所有节点
void print() {
if (head == NULL) {
printf("链表为空,无法打印节点!\n");
return;
}
struct Node* currentNode = head;
do {
printf("%d ", currentNode->data);
currentNode = currentNode->next;
} while (currentNode != head);
printf("\n");
}
int main() {
insert(1);
insert(2);
insert(3);
insert(4);
insert(5);
print(); // 输出:1 2 3 4 5
delete(3);
print(); // 输出:1 2 4 5
search(4); // 输出:链表中存在节点 4
return 0;
}
```
以上代码实现了双向循环链表的基本操作,包括在链表末尾插入节点、在链表中删除节点、在链表中查找节点以及打印链表中的所有节点。
阅读全文