# Double Link List Swap function

This is a discussion on Double Link List Swap function within the C++ Programming forums, part of the General Programming Boards category; K here is my swap function. The only problem i have is what if you want to swap the last ...

1. ## Double Link List Swap function

K here is my swap function. The only problem i have is what if you want to swap the last node it crashes. Plz someone help i have been tryong to figure out a way to get that in like a week now. And we are not spostu swap the data of the node but the full node thanks. here is waht i got any tips be great.
oops forgot the first and last node cause of the NULL and it is different senario and beside that forgot to say taht the last pointer is last first pointer is first.

Code:
```void swap(int nodea,int nodeb)
{
if (nodea>nodeb)
{
int Temp;
Temp=nodeb;
nodeb=nodea;
nodea=Temp;
}

Node* NodeA=first;
Node* NodeB=first;
Node* temp1;
Node* temp2;

for (int x=0;x<nodea;x++)
NodeA=NodeA->next;
for (int x=0;x<nodeb;x++)
NodeB=NodeB->next;

if ((nodea+1)==nodeb||(nodea-1)==nodeb)
{
NodeB->next->prev=NodeA;
NodeA->prev->next=NodeB;
NodeB->prev=NodeA->prev;
NodeA->next=NodeB->next;
NodeA->prev=NodeB;
NodeB->next=NodeA;
}
else
{

temp1=NodeA->next;
temp2=NodeB->prev;

NodeA->next=NodeB->next;
NodeB->prev=NodeA->prev;

NodeB->next=temp1;
NodeA->prev=temp2;

NodeA->next->prev=NodeA;
NodeA->prev->next=NodeA;

NodeB->next->prev=NodeB;
NodeB->prev->next=NodeB;
}

}```

2. A simple solution is to check NodeB->next to see if it is null (I assume that the last element's next pointer is null and the first element's prev pointer is null). You could also check NodeB against last if you store the last element like you do the first. Then if you are swapping with the last element just add an extra else if condition to your if/else and handle it with special code.