C++链表完成头插尾插操作后display函数无法显示内容问题
C++链表插入尾部后无法输出问题排查
核心错误点
- 尾插函数空指针解引用:
insertatend中遍历链表的终止条件写为while (location != NULL),循环结束时location已经是空指针,此时执行location -> link = temp属于非法访问,直接导致程序崩溃,无法执行后续的display函数。正确的遍历条件应为while (location -> link != NULL),循环结束后location指向链表最后一个有效节点,可以正常挂载新的尾节点。 - 头插函数错误修改尾节点标记:全局变量
location本意是记录链表尾节点位置,头插操作不会改变原有尾节点,但你在insertatfirst执行完成后将location赋值为新插入的头节点,导致尾节点标记完全错误,后续操作逻辑混乱。 - 打印函数逻辑不合理:
display中将链表提示语放在了循环内部,会导致每个节点输出前都重复打印一次提示文本,不符合预期。
修复后完整代码
#include<iostream> using namespace std; void createlinklist(); void insertatfirst(); void insertatend(); void display(); struct node { int data; node * link; }; node * start = NULL; node * tail = NULL; // 改名更清晰,避免歧义 void createlinklist() { node * temp = new node; cout << "Enter data in first node: "; cin >> temp -> data; temp -> link = NULL; start = temp; tail = temp; } void insertatfirst() { node * temp = new node; cout << "Enter data for new node at the beginning: "; cin >> temp -> data; temp -> link = start; start = temp; // 头插不修改尾节点,不需要改动tail cout << "Linked list after inserting at head: "; node * p = start; while (p != NULL) { cout << p -> data << " "; p = p -> link; } cout << endl; } void insertatend() { node * temp = new node; cout << "Enter data for new node at the end: "; cin >> temp -> data; temp -> link = NULL; // 直接用tail标记操作,不需要遍历,效率更高 tail -> link = temp; tail = temp; } void display() { // 提示语移到循环外,避免重复打印 cout << "The final linked list is: "; node * p = start; while (p != NULL) { cout << p -> data << " "; p = p -> link; } cout << endl; } int main() { createlinklist(); insertatfirst(); insertatend(); display(); return 0; }
内容的提问来源于stack exchange,提问作者Muhammad Awais
相关产品推荐
相关产品推荐

