链表本身不难,难的是:指针、内存、边界条件。
下面这 10 个坑,基本覆盖初学者 90% 的崩溃现场。
坑 1:忘了给next置 NULL(野指针串链)
错误:
Node* n = malloc(sizeof(Node)); n->data = x; // n->next 未初始化**后果:**遍历时跑飞、随机崩溃。
正确:
n->next = NULL;
坑 2:把“局部变量地址”当节点返回(悬空指针)
错误:
Node* create(int x) { Node n; // 栈变量 n.data = x; n.next = NULL; return &n; // 返回栈地址:函数结束就失效 }**正确:**必须malloc
Node* create(int x){ Node* n = malloc(sizeof(Node)); n->data = x; n->next = NULL; return n; }坑 3:忘了判空就解引用(*head 直接炸)
错误:
Node* cur = head; while (cur->next) { ... } // head 可能是 NULL正确:
for (Node* cur=head; cur!=NULL; cur=cur->next) { ... }坑 4:删除节点后继续用它(Use-After-Free)
错误:
free(cur); cur = cur->next; // cur 已释放,还在用正确:
Node* next = cur->next; free(cur); cur = next;坑 5:删除头节点没处理(头指针没更新)
**典型 bug:**删值命中第一个节点时,链表“看起来没变”。
正确思路:
如果删的是头:
*head = (*head)->next;
坑 6:插入/删除想改 head,却只传了Node* head(改不动)
错误:
void push_front(Node* head, int x) { Node* n = create(x); n->next = head; head = n; // 只改了形参 }**正确:**传二级指针
void push_front(Node** head, int x){ Node* n = create(x); n->next = *head; *head = n; }坑 7:遍历条件写错导致漏最后一个节点
错误:
while (cur->next != NULL) { printf("%d", cur->data); cur=cur->next; } // 最后一个没打印正确:
while (cur != NULL) { ... }坑 8:尾插没处理空链表(head==NULL)
错误:
Node* cur = head; // head 为 NULL while (cur->next) ...正确:
if (*head == NULL) { *head = newNode; return; }
坑 9:内存泄漏(忘记 destroy / 只 free 头)
错误:
free(head); // 只释放了头,其余节点泄漏
正确:
while (head) { Node* next=head->next; free(head); head=next; }
坑 10:打印/调试把指针当 int(格式化输出错)
错误:
printf("%d\n", head); // 64位平台会错
正确:
printf("%p\n", (void*)head);
附:一份“安全版本”的链表骨架(建议你直接收藏)
typedef struct Node { int data; struct Node* next; } Node; Node* create_node(int x){ Node* n = (Node*)malloc(sizeof(Node)); if(!n) return NULL; n->data = x; n->next = NULL; return n; } void push_front(Node** head, int x){ Node* n = create_node(x); n->next = *head; *head = n; } void append(Node** head, int x){ Node* n = create_node(x); if(*head == NULL){ *head = n; return; } Node* cur = *head; while(cur->next) cur = cur->next; cur->next = n; } void destroy_list(Node* head){ while(head){ Node* next = head->next; free(head); head = next; } }