C语言 创建双向循环链表
时间: 2023-12-29 18:03:54 浏览: 76
创建双向循环链表的基本步骤如下:
1. 定义结构体,包含数据和指向前一个和后一个节点的指针。
```
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
```
2. 创建头节点,指向自己。
```
struct Node* head = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
head->prev = head;
head->next = head;
```
3. 插入节点,可以分为在头部插入、在尾部插入和在中间插入三种情况。
在头部插入:
```
struct Node* newNode = NULL;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->prev = head;
newNode->next = head->next;
head->next->prev = newNode;
head->next = newNode;
```
在尾部插入:
```
struct Node* newNode = NULL;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->prev = head->prev;
newNode->next = head;
head->prev->next = newNode;
head->prev = newNode;
```
在中间插入:
```
struct Node* newNode = NULL;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->prev = prevNode;
newNode->next = prevNode->next;
prevNode->next->prev = newNode;
prevNode->next = newNode;
```
4. 删除节点,类似于插入节点,也可以分为删除头节点、删除尾节点和删除中间节点三种情况。
删除头节点:
```
struct Node* temp = NULL;
temp = head->next;
head->next = temp->next;
temp->next->prev = head;
free(temp);
```
删除尾节点:
```
struct Node* temp = NULL;
temp = head->prev;
head->prev = temp->prev;
temp->prev->next = head;
free(temp);
```
删除中间节点:
```
struct Node* temp = NULL;
temp = prevNode->next;
prevNode->next = temp->next;
temp->next->prev = prevNode;
free(temp);
```
完整代码如下:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
int main() {
struct Node* head = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
head->prev = head;
head->next = head;
// 在头部插入节点
struct Node* newNode = NULL;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = 10;
newNode->prev = head;
newNode->next = head->next;
head->next->prev = newNode;
head->next = newNode;
// 在尾部插入节点
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = 20;
newNode->prev = head->prev;
newNode->next = head;
head->prev->next = newNode;
head->prev = newNode;
// 在中间插入节点
struct Node* prevNode = head->next;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = 30;
newNode->prev = prevNode;
newNode->next = prevNode->next;
prevNode->next->prev = newNode;
prevNode->next = newNode;
// 遍历链表
struct Node* temp = head->next;
while (temp != head) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
// 删除头节点
temp = head->next;
head->next = temp->next;
temp->next->prev = head;
free(temp);
// 删除尾节点
temp = head->prev;
head->prev = temp->prev;
temp->prev->next = head;
free(temp);
// 删除中间节点
prevNode = head->next;
temp = prevNode->next;
prevNode->next = temp->next;
temp->next->prev = prevNode;
free(temp);
// 遍历链表
temp = head->next;
while (temp != head) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
return 0;
}
```
阅读全文