Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reverse a linked list?

Tags:

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?

like image 614
user1176235 Avatar asked Jan 31 '12 09:01

user1176235


2 Answers

enter image description here

like image 190
Aquarius_Girl Avatar answered Sep 28 '22 04:09

Aquarius_Girl


The code simply walks the list and inverts the links until it reaches the previous tail, which it returns as the new head.

Before:

Node 1 (Head) -> Node 2 -> Node 3 -> Node 4 (Tail) -> null 

After:

   null <- Node 1 (Tail) <- Node 2 <- Node 3 <- Node 4 (Head) 
like image 36
Michael Borgwardt Avatar answered Sep 28 '22 06:09

Michael Borgwardt