Sunday, June 27, 2010

Code For Reversing the Linked list

We can reverse the linked list in different ways.But the efficient way is given below.
  •    The Idea behind here is making the first node as a last node.
  •    So The Time Complexity for this code is O(n). 
  •    The following one is efficient using three pointers. 

Here is the code

 struct node* reverse(struct node *head)
{    struct node *q,*r,*s;
      q=head;
      r=NULL;
      while(q!=NULL)
     {  s=r;
         r=q;
        q=q->link;
        r->link=s;
      }
    return r;
 }

No comments: