链表输出仅从第二个输入开始,首个数据丢失问题排查与修复
问题分析与代码修复
问题原因
- 首个输入数据被覆盖:在do-while循环的第一次迭代中,程序新建节点并将其设为当前节点
t的后继后,错误地将新输入的数据写入了**当前节点t(即原头节点)**的data字段,而非新创建的节点。这直接覆盖了第一次输入的23,导致首个数据丢失。 - 打印逻辑遗漏最后一个节点:打印环节的循环条件
while(t->next != NULL)会在t指向最后一个节点时终止循环(因为最后一个节点的next为NULL),导致最后一个节点的数据无法被输出。
修复方案
- 修正循环内的数据写入目标:在do-while循环中,新建节点后直接向其写入数据,再将
t移动到新节点,避免覆盖原有节点内容。 - 调整打印循环的终止条件:将循环条件改为
while(t != NULL),确保遍历链表的所有节点。 - 增加空链表边界处理:初始化头指针为
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
相关产品推荐
相关产品推荐

