include <stdio.h>
include <stdlib.h>
// 定义单链表的节点结构
typedef struct Node {
int data;
struct Node *next;
} Node;
// 定义单链表
typedef struct {
Node *head;
} LinkedList;
// 创建链表
LinkedList* createLinkedList() {
LinkedList list = (LinkedList)malloc(sizeof(LinkedList));
list->head = NULL;
return list;
}
// 在链表头部插入节点
void insertAtHead(LinkedList *list, int data) {
Node newNode = (Node)malloc(sizeof(Node));
newNode->data = data;
newNode->next = list->head;
list->head = newNode;
}
// 打印链表
void printLinkedList(LinkedList *list) {
Node *node = list->head;
while (node) {
printf("%d -> ", node->data);
node = node->next;
}
printf("NULL\n");
}
// 释放链表的内存
void freeLinkedList(LinkedList *list) {
Node *node = list->head;
Node *nextNode;
while (node) {
nextNode = node->next;
free(node);
node = nextNode;
}
free(list);
}