You need to enable JavaScript to run this app. C++链表头指针为NULL时尾插元素无输出 代码问题排查
优惠活动
大模型
产品
解决方案
定价
更多

C++链表头指针为NULL时尾插元素无输出 代码问题排查

错误原因

你的代码共有两处核心问题:

  • end函数未按声明返回有效值:函数声明返回Node*类型,但函数体内没有return语句,当你在main中用head = end(head, 8)接收返回值时,会把原有合法的头指针覆盖为无效值,最终得到空链表。
  • 尾插遍历逻辑错误:你写的while(ptr!=NULL)循环结束时ptr已经是空指针,此时执行ptr->next = temp会触发空指针访问异常,正确的逻辑应该是遍历到最后一个非空节点,将循环条件改为while(ptr->next != NULL)即可。
修正后完整代码
#include <bits/stdc++.h>
using namespace std;

class Node
{
public:
    int data;
    Node* next;
};

Node * insert(Node* head, int data)
{
    Node* new_node= new Node();
    new_node->data = data;
    new_node->next = head;
    return new_node;
}

Node * end(Node *head, int data)
{
    Node* ptr = head;
    Node* temp = new Node();
    temp->data = data;
    temp->next = NULL;
    // 修正遍历条件,找到最后一个非空节点
    while(ptr->next != NULL){
        ptr = ptr->next;
    }
    ptr->next = temp;
    // 补充返回头指针
    return head;
}

void display(Node * head)
{
    Node * temp = head;
    while(temp != NULL)
    {
        cout << temp->data << " ";
        temp = temp->next;
    }
}

int main()
{
    Node * head = NULL;
    head = insert(head, 1);
    head = end(head, 8);
    display(head);
    return 0;
}

修正后运行将输出1 8,符合预期功能。

内容的提问来源于stack exchange,提问作者PETULLA MISHRA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 18:12:00