用C语言创建一个双链表,用C语言代码描述
时间: 2023-06-01 10:05:57 浏览: 104
c语言链表的基本操作,代码可直接使用
以下是用C语言实现双向链表的代码示例:
```c
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int data;
struct node *prev;
struct node *next;
} Node;
Node *head = NULL;
Node *tail = NULL;
void insertAtBeginning(int value) {
Node *new_node = (Node*) malloc(sizeof(Node));
new_node->data = value;
new_node->prev = NULL;
new_node->next = head;
if(head != NULL) {
head->prev = new_node;
} else {
tail = new_node;
}
head = new_node;
}
void insertAtEnd(int value) {
Node *new_node = (Node*) malloc(sizeof(Node));
new_node->data = value;
new_node->prev = tail;
new_node->next = NULL;
if(tail != NULL) {
tail->next = new_node;
} else {
head = new_node;
}
tail = new_node;
}
void display() {
Node *current = head;
while(current != NULL) {
printf("%d ",current->data);
current = current->next;
}
}
int main() {
insertAtBeginning(10);
insertAtEnd(20);
insertAtBeginning(30);
insertAtEnd(40);
printf("Doubly linked list is: ");
display();
return 0;
}
```
这个示例代码创建了一个双向链表,实现了在链表头部和尾部插入元素,并能够遍历链表并输出其内容。
阅读全文