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

C++链表头指针初始为NULL时尾部插入操作失效问题求助

问题根因
  • C++默认参数传递为值传递,你当前insert_at_end函数传入的head是原指针的副本:函数内部对head本身的赋值操作仅作用于副本,不会修改main函数中原始头指针的取值。
  • 初始head为NULL时,第一次插入操作仅修改了函数本地的head副本,main中的head始终保持NULL,后续所有插入都不会实际生成可用链表,最终运行时要么输出空链表提示,要么触发空指针访问异常。
  • 提前插入头节点后head不为NULL时,插入逻辑仅修改已有节点的next指针,不需要修改head本身的取值,因此运行正常。
修复方案

共有两种通用修改方式:

  1. 将insert_at_end的头指针参数改为指针引用,让函数内部可以直接修改原始头指针的值(C++专属方案,代码改动最小)
  2. 调整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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:18:01