How can I reverse a linked list?

user1176235 picture user1176235 · Jan 31, 2012 · Viewed 15.3k times · Source

Consider:

 Node reverse(Node head) {
    Node previous = null;
    Node current = head;
    Node forward;

    while (current != null) {
        forward = current.next;
        current.next = previous;
        previous = current;
        current = forward;
    }

    return previous;
}

How exactly is it reversing the list?

I get that it first sets the second node to forward. Then it says current.next is equal to a null node previous. Then it says previous is now current. Lastly current becomes forward?

I can't seem to grasp this and how it's reversing. Can someone please explain how this works?

Answer

Aquarius_Girl picture Aquarius_Girl · Feb 1, 2012

enter image description here