# Help with swapping nodes in a linked list

• 10-18-2005
Axel
Help with swapping nodes in a linked list
I don't understand the logic behind swapping a node in a link list. Currently i have a simple list with customers their names are in a array which is stored in a struct on the linked list node. There's a pointer to the start, from there i just loop around till i get to the end custList->next etc.. all the names are printed.

Now, i can get a reference to the start and next elements in the list. But how exactly do i reference a specific node that i want? and swap it?
:confused:
• 10-18-2005
Quantum1024
You would search thru the nodes untill you find one who's data matches what you're looking for. You can also reference a node by couting thru the list untill you reach a spcific node.
You swap a node by changing the previous node's next pointer to point to the new node and then point the new node's next pointer to the node which followed the node you're swapping out.
• 10-18-2005
Axel
Hmm i haven't had any luck. Are there any simple examples? i.e. two nodes i just want them swapped, i want to get the basic concept figured out first.

I'm trying to get the basic idea, but the actual problem is; i have a linked list with city names they have an x and y co-ordinate. What i want to do is find the shortest path around and reorder the list. I have the basic link list structure and the formula that will be used:

sqrt( ( pow( (x1 - x2), 2) + pow( (y1 - y2), 2) ) );

I'm just having trouble approaching the problem and comparing the link list elements i.e.

if i have A, B, C and D in a map and i have to coordinates, if travelling from A to C to B to D is shorter than A-B-C-D or C-B-F then B and C should be swapped. I have the x and y co-ordinates in my struct of the node.
• 10-18-2005
cbastard
Its a well known problem.just google for shortest path algorithm.
searching:
You have to traverse the list.
Code:

```current =header of list while(current->next!=required val) current=current->next```
there are two methods to swap the link list variable:
1.first change the pointers(next) as told above
2.exchange the values in structure.