链表首尾插入节点代码报错求助:请指出问题及修正方法
链表首尾插入节点的代码错误分析与修正
节点定义
struct Node { int data; struct Node *link; };
头部插入代码的问题与修正
原代码问题
void Shift(struct Node **head, int new_data) { struct Node *New; New = (struct Node *)malloc(sizeof(struct Node)); if (New == NULL) { printf("It is Null\n"); } New->data = new_data; New->link = head; }
- 内存分配失败时,仅打印提示但未终止函数,后续代码会访问空指针
New,触发未定义行为 New->link = head;错误:head是二级指针,应该赋值为*head(原链表的头指针)- 未更新原链表的头指针:新节点作为新的表头,需要将
*head指向New,否则外部的头指针不会变化,插入的节点无法被访问
修正后的头部插入代码
void PushFront(struct Node **head, int new_data) { struct Node *New = (struct Node *)malloc(sizeof(struct Node)); if (New == NULL) { printf("内存分配失败\n"); return; // 分配失败直接返回,避免后续非法访问 } New->data = new_data; New->link = *head; // 指向原表头 *head = New; // 更新表头为新节点 }
尾部插入代码的问题与修正
原代码问题
void Shift(struct Node *head, int new_data) { while (head != NULL) { head = head->link; } struct Node *New; New = (struct Node *)malloc(sizeof(struct Node)); if (New == NULL) { printf("It is Null\n"); } New->link = NULL; New->data = new_data; }
- 遍历结束后
head为NULL,此时你尝试加head->link = New会直接访问空指针,触发崩溃 - 函数参数是一级指针
head,无法修改外部的头指针:如果原链表为空,新节点需要成为表头,但一级指针传参是值传递,外部头指针不会更新 - 内存分配失败未终止函数,存在非法访问风险
- 没有将原链表最后一个节点的
link指向新节点,新节点无法接入链表
你遇到的无限循环原因
当你错误地在遍历后加head->link = New,此时head已经是NULL,赋值操作会破坏内存,导致链表指针混乱,后续遍历链表时可能出现环形结构,从而触发无限输出。
修正后的尾部插入代码
void Append(struct Node **head, int new_data) { // 改名避免和头部插入函数重名 struct Node *New = (struct Node *)malloc(sizeof(struct Node)); if (New == NULL) { printf("内存分配失败\n"); return; } New->data = new_data; New->link = NULL; // 处理空链表情况 if (*head == NULL) { *head = New; return; } // 遍历到最后一个节点(不是NULL) struct Node *temp = *head; while (temp->link != NULL) { temp = temp->link; } temp->link = New; // 最后一个节点指向新节点 }
注意:两个插入函数不要用同一个名字
Shift,建议分别命名为PushFront(头部插入)和Append(尾部插入),避免函数名冲突。
内容的提问来源于stack exchange,提问作者RichardKing
相关产品推荐
相关产品推荐

