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

链表反转函数指针不等判断异常:循环未按预期终止

链表反转函数循环无法终止的问题分析与解决

我编写了一个基于链表首尾节点地址的反转函数,函数中最后一个节点的next成员可能为NULL也可能不为NULL。原本希望当first等于last->next时终止while循环,但循环始终无法正常终止。

存在问题的代码

#include <iostream>
using namespace std;

struct node
{
    int data{};
    node *next{};
    node() = default;
    node(int d, node *n) : data(d), next(n) {}
};

void reverse(node *first, node *last)
{
    node *temp = nullptr;
    node *nextNode = nullptr;
    while (first != last->next)
    {
        nextNode = first->next;
        first->next = temp;
        temp = first;
        first = nextNode;
    }
}

int main()
{
//creation of linked list
    node *n4 = new node(4, nullptr), *n3 = new node(3, n4), *n2 = new node(2, n3), *n1 = new node(1, n2);

    reverse(n1,n4); //call to reverse function
    node *temp = n4; //printing linked list for debugging
    while (temp)
    {
        cout<< temp->data;
        temp = temp->next;
    }
    return 0;
}

问题原因

核心问题在于循环过程中修改了last->next的值,导致终止条件失效:

  • 初始时last->next是固定值(比如示例中的NULL),但在反转last节点时,first指向last,此时first->next = temp会把last->next改成前一个节点的地址。
  • 这就导致循环条件first != last->next中的last->next不再是初始的终止标记,当first走到原终止位置(比如NULL)时,last->next已经变成了其他节点地址,循环无法终止,甚至会触发空指针访问错误。

修正方案

提前保存last->next的初始值,用这个固定的终止标记来判断循环条件,避免后续修改影响判断:

void reverse(node *first, node *last)
{
    node *temp = nullptr;
    node *nextNode = nullptr;
    node *terminator = last->next; // 提前保存终止标记,不受后续指针修改影响
    while (first != terminator)
    {
        nextNode = first->next;
        first->next = temp;
        temp = first;
        first = nextNode;
    }
}

对比可正常运行的实现

另一段能正常运行的代码逻辑是:循环到first等于last时停止,单独处理last节点的next指针,这样就避免了在循环中修改与终止条件相关的指针,因此可以正常结束:

void reverse(node *first, node *last)
{
    node *temp = nullptr, *nextNode;
    while (first != last)
    {
        nextNode = first->next;
        first->next = temp;
        temp = first;
        first = nextNode;
    }
    first->next=temp;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 15:40:33