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

链表打印异常问题:重复输出最后输入的元素

解决链表打印时最后元素重复的问题

嘿,我来帮你揪出这个小bug!这种输入1、2、3后打印重复3的情况,大概率是链表构建或者打印逻辑里踩了常见的小坑,咱们一步步拆解问题:

可能的原因1:节点添加逻辑出错

最常见的问题是没有正确创建新节点,而是反复修改最后一个节点的值。比如你可能写了类似这样的错误代码:

struct Node {
    int data;
    Node* next;
    Node(int val) : data(val), next(nullptr) {}
};

int main() {
    Node* head = nullptr;
    Node* current = nullptr;
    int num;
    cout << "输入数字(负数停止):" << endl;
    while (cin >> num && num >= 0) {
        if (head == nullptr) {
            head = new Node(num);
            current = head;
        } else {
            // 错误:直接覆盖当前节点的数据,没有创建新节点
            current->data = num;
            // 这里也没有移动current指针到新节点
        }
    }
    // 打印逻辑...
}

这种写法下,每次输入新的正数,都会把最后一个节点的data改成新数字,最后链表其实只有一个节点,自然打印时会重复输出最后输入的那个数。

正确的节点添加方式

每次输入正数时,要创建新节点并链接到链表末尾,同时移动current指针到新节点:

while (cin >> num && num >= 0) {
    Node* newNode = new Node(num);
    if (head == nullptr) {
        head = newNode;
        current = head;
    } else {
        current->next = newNode;
        current = newNode; // 移动到新节点,准备下一次添加
    }
}

可能的原因2:打印链表时的循环逻辑错误

另一个常见坑是打印时多遍历了一次最后节点。比如你可能写了这样的错误打印代码:

void printList(Node* head) {
    Node* temp = head;
    while (temp != nullptr) {
        cout << temp->data << " ";
        // 错误:额外打印了最后一个节点
        if (temp->next == nullptr) {
            cout << temp->data << " ";
        }
        temp = temp->next;
    }
}

或者循环条件写错,比如用temp->next != nullptr遍历完所有中间节点后,又重复打印了最后一个节点:

void printList(Node* head) {
    Node* temp = head;
    while (temp->next != nullptr) {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << temp->data << " "; // 这里没问题,但如果不小心写了两次就会重复
    cout << temp->data << " ";
}

正确的打印逻辑

只需要简单遍历每个节点一次即可:

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

你可以先检查这两个地方,大概率就能解决最后元素重复的问题啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:00:51