Thread: swap nodes in doubly linked list

  1. #1
    Registered User
    Join Date
    Mar 2003

    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

    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;

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Waterloo, Texas
    >> 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:

    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;
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
        return std::pow
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;

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
    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, 06:13 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM