【问题标题】:Changing a line in linked list reversal causes error在链表反转中更改一行会导致错误
【发布时间】:2012-04-25 12:54:28
【问题描述】:

这个问题可能是周围最受欢迎的问题之一,在寻找解决方案时,我发现了很多,但下面的代码最适合我。

它实际上做的是创建另一个列表并遍历旧列表并将元素始终添加到新列表的 head 中。

Node *reverseList(Node *oldList)
{
    Node* newList=NULL;

    while(oldList!=NULL)
    {
        Node *temp=oldList;
        oldList=oldList->next;

        temp->next=newList;
        newList=temp;  
    }
    return newList;
}

但是,当我决定在不查看此代码的情况下重新实现此想法时,我更改了 oldList=oldList->next; 的位置并将其放在 newList=temp. 之后

我的问题是它真的有影响吗?我无法理解原因,因为毕竟您是在遍历 oldList。为什么需要在 *temp 声明之后立即完成?

【问题讨论】:

  • 我不确定你的问题是什么。你是说当你改变代码的顺序时,它的行为就会改变?使所有链表操作问题合理化的方法是在一张纸上画一堆方框和箭头。

标签: c++ algorithm data-structures linked-list


【解决方案1】:

做完之后

Node *temp = oldList;

两个指针都指向同一个地方。自从

temp->next = newList;

会覆盖 oldList 的 next 指针(因为它在这个阶段指向与 temp 相同的东西),你需要先从它的 next 指针更新 oldList。

【讨论】:

  • 非常感谢您的精彩解释!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 2013-01-19
  • 2020-11-10
相关资源
最近更新 更多