用C语言写一个双向列表实现头插法
时间: 2023-03-28 20:01:59 浏览: 43
可以使用以下代码实现双向列表的头插法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *prev;
struct node *next;
} Node;
Node *head = NULL;
void insert(int data) {
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = head;
if (head != NULL) {
head->prev = newNode;
}
head = newNode;
}
void printList() {
Node *current = head;
printf("List: ");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
insert(1);
insert(2);
insert(3);
printList();
return ;
}
```
这段代码创建了一个双向列表,并使用头插法插入了三个节点。最后,打印出列表中的所有节点。