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: 49%

You need to log on to convert this article into PDF


Related Blog Items

5 Comments

Leave a comment

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