ok it seems as though when i run the swap function twice, i can unswap the elements that were swapped.
This is a discussion on linked list swap function within the C Programming forums, part of the General Programming Boards category; ok it seems as though when i run the swap function twice, i can unswap the elements that were swapped....
ok it seems as though when i run the swap function twice, i can unswap the elements that were swapped.
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; }
Then again, there's reading the forum rules about bumping 5 YEAR old threads.
Closed.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I support http://www.ukip.org/ as the first necessary step to a free Europe.