c语言创建双向循环链表
时间: 2023-12-03 07:04:27 浏览: 42
双向循环链表是一种特殊的链表,它的每个节点都有两个指针,一个指向前一个节点,一个指向后一个节点,而最后一个节点的后继指针指向头结点,头结点的前驱指针指向最后一个节点。下面是一个简单的 C 语言程序示例,用于创建双向循环链表:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *prev;
struct node *next;
};
struct node *head = NULL;
struct node *tail = NULL;
void create_list(int n);
void display_list();
int main() {
int n;
printf("Enter the number of nodes: ");
scanf("%d", &n);
create_list(n);
printf("Data in the list:\n");
display_list();
return 0;
}
void create_list(int n) {
int i, data;
struct node *newNode;
if (n <= 0) {
printf("List size must be greater than zero.\n");
return;
}
head = (struct node*)malloc(sizeof(struct node));
if (head == NULL) {
printf("Unable to allocate memory.");
return;
}
printf("Enter the data of node 1: ");
scanf("%d", &data);
head->data = data;
head->prev = NULL;
head->next = NULL;
tail = head;
for (i = 2; i <= n; i++) {
newNode = (struct node*)malloc(sizeof(struct node));
if (newNode == NULL) {
printf("Unable to allocate memory.");
break;
}
printf("Enter the data of node %d: ", i);
scanf("%d", &data);
newNode->data = data;
newNode->prev = tail;
newNode->next = head;
tail->next = newNode;
tail = newNode;
head->prev = tail;
}
printf("List created successfully.\n");
}
void display_list() {
struct node *current;
if (head == NULL) {
printf("List is empty.\n");
return;
}
current = head;
printf("List is:\n");
do {
printf("%d\n", current->data);
current = current->next;
} while (current != head);
}
```
在这个程序中,我们定义了一个结构体 `node`,它包含三个成员:`data`,`prev` 和 `next`,分别表示节点的数据、前驱指针和后继指针。我们还定义了两个指针 `head` 和 `tail`,分别指向链表的头结点和尾结点。
在 `create_list` 函数中,我们首先创建头结点,并让 `head` 和 `tail` 指向头结点。然后通过 `for` 循环创建其他节点,并将它们插入到链表的尾部。每个节点的前驱指针指向上一个节点,后继指针指向下一个节点,最后一个节点的后继指针指向头结点,头结点的前驱指针指向最后一个节点。
在 `display_list` 函数中,我们首先判断链表是否为空,然后通过 `do-while` 循环遍历链表,输出每个节点的数据。由于这是一个双向循环链表,循环条件为 `current != head`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)