AI短视频月入过万:揭秘3个真实可行方法与避坑指南
2026/7/15 22:53:08
链表本身不难,难的是:指针、内存、边界条件。
下面这 10 个坑,基本覆盖初学者 90% 的崩溃现场。
next置 NULL(野指针串链)错误:
Node* n = malloc(sizeof(Node)); n->data = x; // n->next 未初始化**后果:**遍历时跑飞、随机崩溃。
正确:
n->next = NULL;
错误:
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; }错误:
Node* cur = head; while (cur->next) { ... } // head 可能是 NULL正确:
for (Node* cur=head; cur!=NULL; cur=cur->next) { ... }错误:
free(cur); cur = cur->next; // cur 已释放,还在用正确:
Node* next = cur->next; free(cur); cur = next;**典型 bug:**删值命中第一个节点时,链表“看起来没变”。
正确思路:
如果删的是头:*head = (*head)->next;
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; }错误:
while (cur->next != NULL) { printf("%d", cur->data); cur=cur->next; } // 最后一个没打印正确:
while (cur != NULL) { ... }错误:
Node* cur = head; // head 为 NULL while (cur->next) ...正确:
if (*head == NULL) { *head = newNode; return; }
错误:
free(head); // 只释放了头,其余节点泄漏
正确:
while (head) { Node* next=head->next; free(head); head=next; }
错误:
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; } }