用c++语言创建双循环链表
时间: 2024-05-09 13:20:29 浏览: 78
以下是用c语言创建双循环链表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 双循环链表节点结构体
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
// 双循环链表结构体
typedef struct DoubleLinkedList {
int size;
Node* head;
Node* tail;
} DoubleLinkedList;
// 创建一个新节点
Node* createNode(int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->prev = NULL;
node->next = NULL;
return node;
}
// 初始化双循环链表
DoubleLinkedList* initDoubleLinkedList() {
DoubleLinkedList* list = (DoubleLinkedList*)malloc(sizeof(DoubleLinkedList));
list->size = 0;
list->head = NULL;
list->tail = NULL;
return list;
}
// 在链表尾部插入新节点
void insertAtTail(DoubleLinkedList* list, int data) {
Node* node = createNode(data);
if (list->size == 0) {
list->head = node;
list->tail = node;
node->prev = node;
node->next = node;
} else {
list->tail->next = node;
node->prev = list->tail;
node->next = list->head;
list->head->prev = node;
list->tail = node;
}
list->size++;
}
// 打印双循环链表
void printDoubleLinkedList(DoubleLinkedList* list) {
if (list->size == 0) {
printf("Empty List\n");
} else {
Node* current = list->head;
printf("List: ");
do {
printf("%d ", current->data);
current = current->next;
} while (current != list->head);
printf("\n");
}
}
int main() {
DoubleLinkedList* list = initDoubleLinkedList();
insertAtTail(list, 1);
insertAtTail(list, 2);
insertAtTail(list, 3);
insertAtTail(list, 4);
printDoubleLinkedList(list);
return 0;
}
```
上述代码中,我们使用了双循环链表节点结构体和双循环链表结构体来定义双循环链表,然后编写了一些函数来操作双循环链表,包括创建新节点、初始化双循环链表、在链表尾部插入新节点、打印双循环链表等。最后,我们在main函数中创建了一个双循环链表并插入了一些节点,然后打印了这个链表。
阅读全文