swap nodes in doubly linked list

This is a discussion on swap nodes in doubly linked list within the C++ Programming forums, part of the General Programming Boards category; i am trying to swap two node in a doubly linked list, i have this code so far.....any hinters Code: ...

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    134

    swap nodes in doubly linked list

    i am trying to swap two node in a doubly linked list, i have this code so far.....any hinters

    Code:
    for(nodeType<Type>* temp=first;temp != NULL; temp=temp->next)
    	
    		if(temp->info < temp->next->info)
    		{
    			nodeType<Type>* temp1=temp->next;
    			nodeType<Type>* temp2=temp->next->previous;
    
    			temp->next->previous=temp->previous;
    			temp->next->next=temp1;
    
    			temp->previous->next=temp->next;
    			temp->previous=temp2;
    			
    		}

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,660
    >> temp2=temp->next->previous;

    You're effectively saying there temp2 = temp;

    Just as temp->next->previous->previous->next == temp, ad infinitum, so just follow the arrows. The easiest way to grasp it is to graph it out on a slip of paper to make it more clear. Second, there are a couple of different qualities of swaps. The best is to code one that will swap ANY two nodes, regardless of whether they are side by side or not. Of course, an adjacent swap algorithm can be more efficient since it optimizes for the simplest case. Anyway, so here's a hint - a node inserter:


    Code:
    nodeType <Type> *
     insert(nodeType <Type> * nod, nodeType <Type> * previous, nodeType <Type> * next)
    {
     if(nod->previous) nod->previous->next = next;
     if(nod->next) nod->next->previous = previous;
     nod->previous = previous;
     nod->next = next;
     if(nod->previous) nod->previous->next = nod;
     if(nod->next) nod->next->previous = nod;
     return nod;
    }



    ITSA
    Socket Library!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Swap nodes in linked list
    By Boaz in forum C Programming
    Replies: 6
    Last Post: 04-29-2009, 08:06 PM
  2. singly linked circular list
    By DarkDot in forum C++ Programming
    Replies: 0
    Last Post: 04-24-2007, 08:55 PM
  3. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM
  4. Linked list with two class types within template.
    By SilasP in forum C++ Programming
    Replies: 3
    Last Post: 02-09-2002, 05:13 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM

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