C++链表头指针初始为NULL时尾部插入操作失效问题求助
问题根因
- C++默认参数传递为值传递,你当前
insert_at_end函数传入的head是原指针的副本:函数内部对head本身的赋值操作仅作用于副本,不会修改main函数中原始头指针的取值。 - 初始
head为NULL时,第一次插入操作仅修改了函数本地的head副本,main中的head始终保持NULL,后续所有插入都不会实际生成可用链表,最终运行时要么输出空链表提示,要么触发空指针访问异常。 - 提前插入头节点后
head不为NULL时,插入逻辑仅修改已有节点的next指针,不需要修改head本身的取值,因此运行正常。
修复方案
共有两种通用修改方式:
- 将
insert_at_end的头指针参数改为指针引用,让函数内部可以直接修改原始头指针的值(C++专属方案,代码改动最小) - 调整
insert_at_end返回值为Node*,返回修改后的头指针地址,调用时将返回值赋值给原头指针变量
修正后完整代码(指针引用方案)
#include <bits/stdc++.h> using namespace std; class Node { public: int data; Node *next; }; // 仅修改参数为Node* &head即可 void insert_at_end(Node *&head, int data) { Node *temp = new Node(); temp->data = data; temp->next = NULL; if (head == NULL) { head = temp; } else { Node *last = head; while (last->next != NULL) { last = last->next; } last->next = temp; cout << "Inserted " << data << " at the End \n"; } } void printList(Node *head) { cout << "List : \n"; Node *temp = head; if (temp == NULL) cout << "Forgive me !"; while (temp != NULL) { cout << "\t" << temp->data << ""; temp = temp->next; } } int main() { Node *head = NULL; insert_at_end(head, 12); insert_at_end(head, 16); insert_at_end(head, 71); insert_at_end(head, 81); insert_at_end(head, 91); printList(head); return 0; }
内容的提问来源于stack exchange,提问作者Prince Kumar
相关产品推荐
相关产品推荐

