Danny from Addis Ababa, Ethiopia
Swapping two nodes given their keys key1 and key2, has two cases.
Case 1: Swapping Adjacent nodes
Case 2: Swapping non-adjacent ones
First find their addresses (Sometimes the swap function is given the addresses (ptrs))
Code:
ptr1 = search_node(key1);
ptr2 = search_node(key2);
//then, check whether they are adjacent or not
if(ptr1->next==ptr2||ptr2->next==ptr1) //Adjacent?
// Code
else // Not Adjacent
// Code
// Here is a code if they are not adjacent, I know it looks complex, maybe it is, but drawing a pictorial diagram helps a lot
{
pptr1=find_previous(key1); // pptr1 is the previous of ptr1 (the node before the first node to be swapped)
pptr2=find_previous(key2); // pptr2 is previous of ptr1
pptr1->next=ptr1->next;
pptr2->next=ptr2->next;
ptr2->next=pptr1->next;
pptr1->next=ptr2;
ptr1->next=pptr2->next;
pptr2->next=ptr1;
}