You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:15:02