1. ## Swap nodes in linked list

hi all, right i am trying to swap two nodes around in a linked list, as part of a sort functions. How while swapping the nodes a round i am tryin to take into account if the nodes been swaped are at the start or end of the linked list, how i have written the following, but its does not work correctly (makes an node within the linked lists disaprear) have you got any ideas whats wrong or do any of you have a function which does what i am looking for that i could have

regards BOAZ

Code:
```void swapNodes(pre_rec temp, pre_rec temp1)
{
pre_rec templeft, tempright;

templeft = temp->prev;
tempright = temp1->next;

temp->next = temp1;
temp1->prev = temp;

if (templeft != NULL)
{
templeft->next = temp1;
temp1->prev = templeft;
}
else
{
temp1->prev = NULL;
}

if (tempright != NULL)
{
tempright->prev = temp;
temp->next = tempright;
}
else
{
temp->next = NULL;
}
}```

2. This is what I'd do:
Code:
```void Swap(NODE** Node1, NODE** Node2)
{
NODE* Temp = (*Node1);
(*Node1) = (*Node2);
(*Node2) = Temp;
}

void SwapNodes(NODE* Node1, NODE* Node2)
{
//Repoint the nodes around the first node
if(Node1->Prev) Node1->Prev->Next = Node2;
if(Node1->Next) Node1->Next->Prev = Node2;

//Repoint the nodes around the second node
if(Node2->Prev) Node2->Prev->Next = Node1;
if(Node2->Next) Node2->Next->Prev = Node1;

//Swap the Next/Prev pointers for the two nodes
Swap(&Node1->Next, &Node2->Next);
Swap(&Node1->Prev, &Node2->Prev);
}```
EDIT: It even works if they are next to each other or if they are the same nodes, which it doesn't seem to do at a first glance .

3. ## Swap nodes in linked list

Hi,
i have written a small code for this. have a look at it

insert
Code:
```void swapNodes(node *p, node *q) {
printf("\nNode to be swapped p = %d\t q = %d\n", p->val, q->val);
node *prevP, *prevQ, *temp;
// check if one of it is head or not

for(prevP = head; prevP->next != p; prevP = prevP->next);
for(prevQ = head; prevQ->next != q; prevQ = prevQ->next);
prevP->next = q;
temp = q->next;
q->next = p->next;
prevQ->next = p;
p->next = temp;
} else {
prevP = prevQ = NULL;
for(prevQ = head; prevQ->next != q; prevQ = prevQ->next);
prevQ->next = p;
} else {
for(prevP = head; prevP->next != p; prevP = prevP->next);
prevP->next = q;
}
temp = q->next;
q->next = p->next;
p->next = temp;
}
}```
Regards,
Sandeep Patra

4. What is this going to be called from?
If it's inside a sorting algorithm then you're probably going to have a lot more problems than you realise.

5. Hm, so that's how I coded 6 years ago...

6. whats a node ?

7. A node is like a space in a book shelf - it can hold things. You decide via your program, what that "thing" will be (a struct is common), and you decide via pointers on the link, what shelf and column you want that "thing" to rest upon.

Each node is connected to another node, which makes the term "linked list" a good one.