#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node *next;
};
// 创建新节点
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// 创建链表
struct Node* createList(int values[], int size) {
struct Node* head = NULL;
for (int i = 0; i < size; i++) {
struct Node* newNode = createNode(values[i]);
newNode->next = head;
head = newNode;
}
return head;
}
// 在头部插入节点
struct Node* insertAtHead(struct Node* head, int value) {
struct Node* newNode = createNode(value);
newNode->next = head;
return newNode;
}
// 遍历并打印链表
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
int main() {
int values[] = {1, 2, 3, 4, 5};
int size = sizeof(values) / sizeof(values[0]);
struct Node* head = createList(values, size);
printf("Original List: ");
printList(head);
head = insertAtHead(head, 0);
printf("List after inserting 0 at head: ");
printList(head);
return 0;
}