繁体   English   中英

反转与头节点的链表

[英]reversing a linked list with the head node

好吧,似乎我正陷入无限循环,试图反转此列表。 所以说我有一些随机数,例如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问题,该问题显示了如何执行反向单链列表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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM