C语言建立一个双向循环链表
时间: 2023-09-17 09:07:44 浏览: 133
双向循环链表是一种链表结构,每个节点都包含指向前驱节点和后继节点的指针。它与单向链表不同之处在于,双向循环链表的尾节点指向头节点,头节点的前驱指向尾节点,形成一个环形结构。
以下是一个简单的双向循环链表的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义双向循环链表节点结构体
typedef struct node{
int data;
struct node *prev;
struct node *next;
} Node;
// 定义双向循环链表结构体
typedef struct dlist{
Node *head;
Node *tail;
} DList;
// 初始化双向循环链表
DList* initDList(){
DList *list = (DList*) malloc(sizeof(DList));
list->head = NULL;
list->tail = NULL;
return list;
}
// 创建新节点
Node* createNode(int data){
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
// 在链表尾部插入新节点
void insertAtTail(DList *list, int data){
Node *newNode = createNode(data);
if(list->head == NULL){
list->head = newNode;
list->tail = newNode;
newNode->prev = list->tail;
newNode->next = list->head;
} else {
newNode->prev = list->tail;
newNode->next = list->head;
list->tail->next = newNode;
list->head->prev = newNode;
list->tail = newNode;
}
}
// 在链表头部插入新节点
void insertAtHead(DList *list, int data){
Node *newNode = createNode(data);
if(list->head == NULL){
list->head = newNode;
list->tail = newNode;
newNode->prev = list->tail;
newNode->next = list->head;
} else {
newNode->prev = list->tail;
newNode->next = list->head;
list->head->prev = newNode;
list->tail->next = newNode;
list->head = newNode;
}
}
// 删除指定节点
void deleteNode(DList *list, Node *delNode){
if(delNode == list->head && delNode == list->tail){
list->head = NULL;
list->tail = NULL;
} else if(delNode == list->head){
list->head = delNode->next;
list->tail->next = list->head;
list->head->prev = list->tail;
} else if(delNode == list->tail){
list->tail = delNode->prev;
list->tail->next = list->head;
list->head->prev = list->tail;
} else {
delNode->prev->next = delNode->next;
delNode->next->prev = delNode->prev;
}
free(delNode);
}
// 打印双向循环链表
void printDList(DList *list){
if(list->head == NULL){
printf("Empty List\n");
} else {
Node *current = list->head;
do{
printf("%d ", current->data);
current = current->next;
} while(current != list->head);
printf("\n");
}
}
int main(){
DList *list = initDList();
insertAtTail(list, 1);
insertAtTail(list, 2);
insertAtTail(list, 3);
insertAtHead(list, 0);
printDList(list);
deleteNode(list, list->head->next);
printDList(list);
return 0;
}
```
以上是一个简单的双向循环链表的实现,代码中包含了初始化链表、创建新节点、在链表尾部插入新节点、在链表头部插入新节点、删除指定节点、打印链表等函数。可以根据实际需求进行调整和扩展。
阅读全文