Monday, August 27, 2012

Reversing singly Linked List - Explanation

I have searched some sites to know how they are reversing linked list , yeah I found so many sites but none of them are explained . So , I conclude it  to do in my blog



Below are the working piece of code 

#include <iostream.h>
#include <conio.h>

class Node
{
  public:
      int data ;
      Node * next ;
      Node(int in){data = in; }     // public param cons
   
      };



Node* Reverse(Node * head )
 {
          Node * temp = NULL ;
          Node * np = NULL;
       
        while (head)
          {
           temp = head->next;
           head->next = np;
           np = head ;
           head = temp;    
       
          }
          return np ;
           
 }


  void Display(Node * head )
   {
      while (head)
      {
       printf("%d \t" , head->data);
       head = head-> next ;  
      }
   }



main()
{
   Node * obj1= new  Node(10) ;
   Node * obj2= new  Node(20) ;
   Node * obj3= new  Node(30) ;
   Node * obj4= new  Node(40) ;
 
   obj1->next = obj2 ;
   obj2->next = obj3 ;
   obj3->next = obj4 ;
 
   printf("Before reversing ");  
   Display(obj1);  
     
   Node * head =  Reverse(obj1);
 
   printf("\n After  reversing ");  
   Display(head);
   getch();  
     
}



Lets see the explanation of Important lines 
  before getting in to that , you need two variable
1. temp -> used to hold next element pointer and given back the address to head
2. np    -> Assign it to head->next

lets discuss the code line by line

step1 :        temp = head->next;  
 take the information of next , so that we can play with head->next

step2:        head->next = np ;
 yeah , In the next line we are changing head->next  ( anyway we are having this info in temp   for later use)
initially np  is null , but from the second iteration it has the info of prev element

step3:       np = head ;
yeh , this step does the same what we want in step 2

step4:    head = temp ;

finally head should move to next element . fortunately this info is stored in temp 


thats all dudes , np will become your new head pointer .

 It may not be the great explanation , but it will be used to the beginners .
 


No comments:

Post a Comment