linked list swap function

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....

  1. #31
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335
    ok it seems as though when i run the swap function twice, i can unswap the elements that were swapped.

  2. #32
    Registered User
    Join Date
    Dec 2010
    Posts
    1

    Swap nodes in Linked List

    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;
    }
    
    
    

  3. #33
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,851
    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.

Page 3 of 3 FirstFirst 123
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help! Placement of nodes in a Linked List
    By lostmyshadow in forum C Programming
    Replies: 6
    Last Post: 12-17-2007, 01:21 PM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 03:39 PM
  3. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 07:39 AM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 06:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21