gpt4 book ai didi

java - 用头节点反转链表

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

好吧,我似乎遇到了一个无限循环,试图反转这个列表。假设我有一些随机数,例如 4,5,6,7,我试图将其反转为 7,6,5,4。我从头部的节点开始,并将其添加到最后一个节点,直到我得到最终列表(IE 7,4 -> 7,5,4,),但我的每一次尝试都给了我无限循环。

    public void Reversing() {
Node<E> currently = this.head;//set it to head to loo[
Node<E> last = this.head;
Node<E> temp = this.head; //not used anymore

last=lastNode();//gets the last item in the list

while (currently != null) {//loop until not null
last.next=currently;
currently=currently.next;

if(last.info==currently.info){//break out of loop
break;
}
}
}

最佳答案

您正在反转单链表。请参阅这个SO问题,它展示了如何做到这一点Reverse Singly Linked List Java

我将复制答案:

Node<E> reversedPart = null;
Node<E> current = head;
while (current != null) {
Node<E> next = current.next;
current.next = reversedPart;
reversedPart = current;
current = next;
}
head = reversedPart;

关于java - 用头节点反转链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29554327/

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