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

C++反转链表后显示异常问题求助

问题定位

你的代码核心问题出在displayList()函数中:该函数直接修改了全局的head指针。第一次调用displayList()时,遍历过程会把head逐步移动到链表的末尾(最终变为NULL),导致后续的reverse()函数拿到的curr初始值就是NULL,无法执行反转逻辑,第二次displayList()自然也没有输出。

修复方案

修改displayList()函数,使用临时指针遍历链表,不要改动原head指针:

void displayList()
{
    // 用临时指针temp遍历,保留原head的指向
    struct node *temp = head;
    while (temp != NULL)
    {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << endl;
}
完整修复后的代码示例
#include <iostream>
using namespace std;

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

struct node *head = NULL;

void createNode(int val) {
    struct node *newNode = new node();
    newNode->data = val;
    newNode->next = head;
    head = newNode;
}

void reverse()
{
    struct node *curr = head;
    struct node *next = NULL;
    struct node *prev = NULL;

    while (curr != NULL)
    {
        next = curr->next;
        curr->next = prev;

        prev = curr;
        curr = next;
    }
    head = prev;
}

void displayList()
{
    struct node *temp = head;
    while (temp != NULL)
    {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << endl;
}

int main(){
    createNode(100);
    createNode(310);
    createNode(150);
    createNode(300);
    createNode(500);

    cout << "Original List" << endl;
    displayList();

    cout << endl << "Reversed List" << endl;
    reverse();
    displayList();

    return 0;
}

这样修改后,displayList()不会影响原链表的head指针,reverse()可以正常反转链表,两次displayList()都能正确输出内容。

内容的提问来源于stack exchange,提问作者Kaif Imran Shariff

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:35:19