简体   繁体   English

反转与头节点的链表

[英]reversing a linked list with the head node

Well it seems like I'm running into a infinite loop trying to reverse this list. 好吧,似乎我正陷入无限循环,试图反转此列表。 so say I have some random numbers like 4,5,6,7 and I was trying reverse it to 7,6,5,4. 所以说我有一些随机数,例如4,5,6,7,而我试图将其反转为7,6,5,4。 I started with the node at the the head and added it to end the last node until i get the final list(IE 7,4 ->7,5,4,) but every I've attempted was giving me infinite loops. 我从头上的节点开始,然后将其添加到最后一个节点的末端,直到获得最终列表(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;
        }  
    }
}

You are reversing a singly linked list. 您正在反转一个单链列表。 See this SO question that shows how to do it Reverse Singly Linked List Java 看到这个SO问题,该问题显示了如何执行反向单链列表Java

I'll copy in the answer: 我将复制答案:

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