Wednesday, February 4, 2015

Reversing a single linked list !



Hello everybody !

This one questions is one of most commonly asked interview questions if you appear for a system programming job . Let me try to write the program for it in most simple way .

Let us consider we have 4 nodes A->B->C->D , to arrange these nodes in reverse order , let us first


  • Take the first node 'A' and detach from the link , 
  • Make the next of A as NULL 
  • Make B as root 


Now , let us go through the first list and detach it from main link and connect it to second link . 


We need to repeat these steps till we reach NULL for the main list , once we are done with the traversing  - its the time for declaring new head as our head :-)

You can get the C code for the same below .


void reverse_list()
{
  struct list *temp ;

  new = head ;

/*Detaching the first node from the main list */
  temp =head->next;
  head = head->next;
  new->next =NULL;

/*Traverse through the main list and attach each node to new list 
   that we are trying to create !*/

  while (temp!= NULL)
  {
    temp = head->next;
    head->next=new;
    new = head ;
    head =temp;
  }

  head = new;

}

Adding & displaying a single linked list you can take as exercise  !!


Enjoy reversing !!





No comments:

Post a Comment