c语言写双向链表头部插入的代码
时间: 2023-09-15 20:23:01 浏览: 85
以下是C语言写双向链表头部插入的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
struct Node* head = NULL;
void insertAtHead(int value) {
//创建一个新结点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
//设置结点的值
newNode->data = value;
newNode->prev = NULL;
//头结点为空时,将新结点设为头结点
if (head == NULL) {
newNode->next = NULL;
head = newNode;
return;
}
//将新结点插入链表头部
head->prev = newNode;
newNode->next = head;
head = newNode;
}
void printList() {
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
insertAtHead(1);
insertAtHead(2);
insertAtHead(3);
insertAtHead(4);
printList();
return 0;
}
```
希望对你有所帮助,还有什么问题要问的吗?
阅读全文