Could you please help me debug this code to swap two node of double link list? I am not able to figure out what i am doing wrong :(
here is the code:
Suppose node1->next == node2 && node2->prev == node1
. Now let's trace:
if(node1->next!=NULL)
{
node1->next->prev=node2;
}
Now node2->prev
points to node2
itself!
if(node2->prev!=NULL)
{
node2->prev->next=node1;
}
Now node2->next
points to node1
, which is ok for now.
Recall that node1->next
still points to node2
, and node2->next
points to node1
.
tmp=node1->next; // == node2
node1->next=node2->next; // == node1 (!)
node2->next=tmp; // == node2
So we have node1->next
pointing to node1
, and node2->next
to node2
. Clearly wrong.
Recall that node2->prev points to node2
, although node1->prev
is correct.
tmp=node1->prev; // correct
node1->prev=node2->prev; // == node2
node2->prev=tmp; // correct
So node1->prev
points to node2
, which is correct.
But node1->next
and node2->next
are still wrong!
How to solve this? It's not a one-liner to solve, as there are a couple special cases.
Maybe detect the special case I described and have separate code for it (and don't forget about that other special case).
Writing that code is left as an exercise to the reader ;)