Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

30
Mar

Reversing a double linked list

Related Blog Items

refer double linked list post for information about double linked list. Here in this post we will be discussing about reversing a double linked list.

Here is the pictorial representation of our algo…
reversing double linked list

in our routine we will swap our next, prev pointers of nodes to reverse the double linked list… this routine capable of reversing entire list for given any node in the double linked list.

The below routine takes input as any node in double linked list and reverse the entire double linked list and returns same node pointer.

Node *reverselist(Node *head)
{
  Node* n = head;
  Node *tmp, *tmp2;
  Node* after = head->next;
  Node* before = head->prev;
 
  //reverse all nodes after n (if any)
 
  //now reverse nodes after head
  while(n && after)
  {
    tmp = after->next;
    tmp2 = after;
 
    after->next = n;
    n->prev = after;
 
    after = tmp;
    n = tmp2;
  }
  //make the last node prev ptr points to NULL
  n->prev = NULL;
 
  //search all nodes before n (if any)
  n = head;
 
  //now reverse all nodes before head
  while(before && n)
  {
    tmp = before->prev;
    tmp2 = before;
 
    before->prev = n;
    n->next = before;
 
    before = tmp;
    n = tmp2;
  }
  //make the first node next ptr points to NULL
  n->next = NULL;
 
  return head;
}

any comments welcome…

Popularity: 51%

You need to log on to convert this article into PDF


Related Blog Items

4 Comments

  • Mike  said:

    overall, very good articles, keep the good work..


  • Lucas  said:

    good work


  • jazzyg  said:

    In case of dounly link list, its pretty eay to reverse it. Simply reverse prev and Next pointer in a node. Fot head, set prev = Null and for Tail, Next = Null


  • Kanza  said:

    Hello!
    Well the information given in your website is proved to be very useful for me. I could not find this information in any other website. Specially the reversing of linked lists.
    Thank You ,
    Kanza


Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image