单向链表是数据结构中最基础也最常用的线性结构之一,由一系列节点组成。每个节点包含数据域存储数据和指针域存储下一个节点的地址,节点间通过指针串联形成链式结构。相比数组,链表插入删除高效,但随机访问需遍历。
一、单向链表的基本结构
定义链表节点结构是所有操作的基础。
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
typedef struct Node {
int data; // 数据域
struct Node* next; // 指针域
} Node;
// 创建新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("内存分配失败\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
节点通过 next 指针连接,最后一个节点的 next 为 NULL 表示链表结束。
二、单向链表的销毁
销毁链表需释放所有节点内存,避免内存泄漏。步骤为遍历链表并逐个释放节点。
void destroyList(Node** head) {
if (head == NULL || *head == NULL) return;
Node* current = *head;
Node* nextNode;
while (current != NULL) {
nextNode = current->next;
free(current);
current = nextNode;
}
*head = ;
}


