Friday, June 26, 2015

Reversing a linked list


Reversing a linked list

Input : 1->2->3->4->5
Ouput : 5>-4->-3>-2->1

So the code goes here :
public void reverse(ListNode head){
    ListNode current = head;
    ListNode next;
    ListNode prev=null;
    while(current != null){
         next = current.next;
         next->null
         current.next = prev;
         current.next->4->3->2->1
         current->5->4->3->2->1
         prev = current;
         prev->5->4->3->2->1
         current = next;
         current->null;
   }
   head = prev;
}

Understanding the code:

Say the list is :
(head)->1->2->3->4->5

Node current = head;
current->1->2->3->4->5
Node next;
next->null;
Node prev = null;
prev->null

//in the loop
//1st iteration
next = current.next;
next->2->3->4->5
current.next = prev;
current.next->null
current->1
prev = current;
prev->1
current = next;
current->2->3->4->5

//2nd iteration
next = current.next;
next->3->4->5
current.next = prev;
current.next->1
current->2->1
prev = current;
prev->2->1
current = next;
current->3->4->5

//3rd iteration
next = current.next;
next->4->5
current.next = prev;
current.next->2->1
current->3->2->1
prev = current;
prev->3->2->1
current = next;
current->4->5

//4th iteration
next = current.next;
next->5
current.next = prev;
current.next->3->2->1
current->4->3->2->1
prev = current;
prev->4->3->2->1
current = next;
current->5

//5th iteration
next = current.next;
next->null
current.next = prev;
current.next->4->3->2->1
current->5->4->3->2->1
prev = current;
prev->5->4->3->2->1
current = next;
current->null;

prev points to the head of the linked list
prev->5->4->3->2->1

It's reversed.