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

链表输出仅从第二个输入开始,首个数据丢失问题排查与修复

问题分析与代码修复

问题原因

  • 首个输入数据被覆盖:在do-while循环的第一次迭代中,程序新建节点并将其设为当前节点t的后继后,错误地将新输入的数据写入了**当前节点t(即原头节点)**的data字段,而非新创建的节点。这直接覆盖了第一次输入的23,导致首个数据丢失。
  • 打印逻辑遗漏最后一个节点:打印环节的循环条件while(t->next != NULL)会在t指向最后一个节点时终止循环(因为最后一个节点的next为NULL),导致最后一个节点的数据无法被输出。

修复方案

  1. 修正循环内的数据写入目标:在do-while循环中,新建节点后直接向其写入数据,再将t移动到新节点,避免覆盖原有节点内容。
  2. 调整打印循环的终止条件:将循环条件改为while(t != NULL),确保遍历链表的所有节点。
  3. 增加空链表边界处理:初始化头指针为NULL,避免用户直接选择不输入数据时出现空指针异常。

修改后的代码

#include<iostream>
using namespace std;

struct node
{
    int data;
    node* next;
};

int main()
{
    char ch;

    node* n;
    node* t;
    node* h = NULL; // 初始化头指针为NULL,处理空链表情况

    cout << "Linked list is created.Now You can write data into it." << endl;
    cout << "Enter data into the linked list:";
    
    // 创建第一个节点并写入数据
    n = new node();
    cin >> n->data;
    h = n;
    t = n;

    cout << "do you want to enter more data into the linked list?(y/n):";
    cin >> ch;

    if (ch == 'y' || ch == 'Y') {
        do {
            n = new node();
            cout << "Enter data into the linked list:";
            cin >> n->data; // 直接向新节点写入数据
            t->next = n;
            t = n; // 移动t到新节点
            cout << "do you want to enter more data into the linked list?(y/n):";
            cin >> ch;
        } while (ch == 'Y' || ch == 'y');
    }
    
    if (t != NULL) { // 避免空链表时t为NULL的情况
        t->next = NULL;
    }

    cout << "\n\n\n=================================\n\n\n";
    
    cout << "Do you want to print data on the linked list?(y/n):";
    cin >> ch;
    if (ch == 'y' || ch == 'Y') {
        t = h;
        while (t != NULL) { // 遍历所有节点,包括最后一个
            cout << t->data << endl;
            t = t->next;
        }
    }

    // 释放链表内存,避免内存泄漏
    t = h;
    while (t != NULL) {
        node* temp = t;
        t = t->next;
        delete temp;
    }

    return 0;
}

内容的提问来源于stack exchange,提问作者Majeed I

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:25:42