gpt4 book ai didi

java - 单链表还原中的错误

转载 作者:行者123 更新时间:2023-12-02 09:11:39 25 4
gpt4 key购买 nike

单链表反转算法中的无限循环。我尝试在一张纸上编写代码,但仍然找不到错误

<小时/>
    public void reverse ()
{
Node pointer = list;
Node newList = new Node();
Node temp = new Node();
Node tempMoving = new Node();

if (pointer != null)
{
newList = pointer;

while (pointer.next != null)
{
System.out.println ("loop");
temp = pointer;
pointer = pointer.next;
temp.next = pointer.next;
tempMoving = pointer;
tempMoving.next = newList;
newList = tempMoving;
}
}

list = newList;
}
<小时/>

我设想这个算法要做的是,当它移动到一个新节点时,它会将该节点放入新列表的开头,并且它将不断重复,直到到达末尾。但是,它只打印“循环”:(

最佳答案

您可以简单地执行以下操作:

public void reverse() {
// Assuming `head` is the first node in linked list
Node current = head, previous = null, forward = null;
while (current.next != null) {
forward = current.next;
current.next = previous;
previous = current;
current = forward;
}
head = current;
head.next = previous;
}

关于java - 单链表还原中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59364449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com