用C语言写一个双向链表实现头插法
时间: 2023-03-28 22:01:56 浏览: 119
双向链表C语言实现
可以的,以下是用 C 语言实现双向链表的头插法代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
void insertAtHead(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
(*head)->prev = newNode;
newNode->next = *head;
*head = newNode;
}
void printList(Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
}
int main() {
Node* head = NULL;
insertAtHead(&head, 1);
insertAtHead(&head, 2);
insertAtHead(&head, 3);
insertAtHead(&head, 4);
printList(head);
return ;
}
阅读全文