c语言实现双向循环链表
时间: 2023-05-27 07:06:49 浏览: 157
双向循环链表是一种常用的数据结构之一,可以在链表中进行快速的插入、删除和查找操作。以下是一种简单的C语言实现双向循环链表的代码:
```
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *prev;
struct node *next;
};
struct node *createNode(int data) {
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
void insertAtBegin(struct node **head, int data) {
struct node *newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
(*head)->next = *head;
(*head)->prev = *head;
} else {
struct node *last = (*head)->prev;
newNode->next = *head;
newNode->prev = last;
last->next = newNode;
(*head)->prev = newNode;
*head = newNode;
}
}
void insertAtEnd(struct node **head, int data) {
struct node *newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
(*head)->next = *head;
(*head)->prev = *head;
} else {
struct node *last = (*head)->prev;
newNode->prev = last;
newNode->next = *head;
last->next = newNode;
(*head)->prev = newNode;
}
}
void deleteNode(struct node **head, int data) {
if (*head == NULL) {
printf("List is empty.\n");
return;
}
struct node *cur = *head;
struct node *prev = NULL;
while (cur->data != data && cur->next != *head) {
prev = cur;
cur = cur->next;
}
if (cur->data != data) {
printf("%d not found in list.\n", data);
return;
}
if (cur == *head && cur->next == *head) {
*head = NULL;
free(cur);
return;
}
if (cur == *head) {
*head = cur->next;
}
struct node *next = cur->next;
prev->next = next;
next->prev = prev;
free(cur);
}
void displayList(struct node *head) {
if (head == NULL) {
printf("List is empty.\n");
return;
}
printf("List: ");
struct node *cur = head;
do {
printf("%d ", cur->data);
cur = cur->next;
} while (cur != head);
printf("\n");
}
int main() {
struct node *head = NULL;
insertAtBegin(&head, 10);
insertAtBegin(&head, 20);
insertAtEnd(&head, 30);
insertAtEnd(&head, 40);
displayList(head);
deleteNode(&head, 20);
deleteNode(&head, 50);
displayList(head);
return 0;
}
```
在这个例子中,我们使用了一个结构体来存储每个节点的数据和指向前一个和后一个节点的指针。我们还定义了一些操作函数,如创建新节点、在链表头部和尾部插入新节点、删除节点和显示链表等。在主函数中,我们创建了一个双向循环链表并进行了一些操作,最后输出链表的内容。
阅读全文