2026/1/2 10:39:47
网站建设
项目流程
东莞市视频直播网站开发,北京搬家公司排名前十名电话,定制公司网站建设,分类信息网站的建设维护链表本身不难#xff0c;难的是#xff1a;指针、内存、边界条件。
下面这 10 个坑#xff0c;基本覆盖初学者 90% 的崩溃现场。坑 1#xff1a;忘了给 next 置 NULL#xff08;野指针串链#xff09;错误#xff1a;Node* n malloc(sizeof(Node));
n-data x; …链表本身不难难的是指针、内存、边界条件。下面这 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; // 返回栈地址函数结束就失效 }**正确**必须mallocNode* 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* curhead; cur!NULL; curcur-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); curcur-next; } // 最后一个没打印正确while (cur ! NULL) { ... }坑 8尾插没处理空链表headNULL错误Node* cur head; // head 为 NULL while (cur-next) ...正确if (*head NULL) { *head newNode; return; }坑 9内存泄漏忘记 destroy / 只 free 头错误free(head); // 只释放了头其余节点泄漏正确while (head) { Node* nexthead-next; free(head); headnext; }坑 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; } }