# swap nodes in doubly linked list

• 09-15-2003
noob2c
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;                                         }```
• 09-15-2003
Sebastiani
>> 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; }```