用C语言写个双向链表代码
时间: 2023-04-08 22:03:08 浏览: 76
好的,我可以回答这个问题。以下是一个简单的双向链表的 C 语言代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
struct Node* head = NULL;
void insertAtBeginning(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = head;
if (head != NULL) {
head->prev = newNode;
}
head = newNode;
}
void insertAtEnd(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
newNode->prev = NULL;
head = newNode;
return;
}
struct Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
newNode->prev = current;
}
void display() {
struct Node* current = head;
if (head == NULL) {
printf("List is empty\n");
return;
}
printf("Nodes of doubly linked list: \n");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
insertAtEnd(1);
insertAtBeginning(2);
insertAtEnd(3);
insertAtBeginning(4);
display();
return 0;
}
```
这个代码实现了双向链表的基本功能,包括在链表头和尾插入节点,并能够遍历链表并输出节点的值。