简体   繁体   中英

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. 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.

    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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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