用c语言写一个双向链表
时间: 2023-02-20 11:02:06 浏览: 112
下面是一个使用 c 语言实现双向链表的简单代码示例:
```
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
struct node *prev;
};
struct node *head = NULL;
struct node *tail = NULL;
// 在链表头部插入数据
void insert_at_head(int data) {
struct node *new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = data;
new_node->prev = NULL;
new_node->next = head;
if (head != NULL) {
head->prev = new_node;
}
head = new_node;
if (tail == NULL) {
tail = new_node;
}
}
// 在链表尾部插入数据
void insert_at_tail(int data) {
struct node *new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
new_node->prev = tail;
if (tail != NULL) {
tail->next = new_node;
}
tail = new_node;
if (head == NULL) {
head = new_node;
}
}
// 打印链表中的数据
void print_list() {
struct node *temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
insert_at_head(1);
insert_at_head(2);
insert_at_tail(3);
insert_at_tail(4);
print_list();
return 0;
}
```
运行结果:
```
2 1 3 4
```
这个示例代码实现了双向链表的常见操作,包括在链表头部和尾部插入数据,以及打印链表中的数据。
阅读全文
相关推荐
![](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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)