1. writting swap function

i want to write a swap function for a singly linked list. the function should take 2node pointers as input parameters and exchange their place in the linked list. this is what i tried out :
Code:
```
void swap(node *p,node *q)
{
/*assigning the previous and current nodes*/
node *pprev,*qprev;
node *pcurr,*qcurr;
node *temp;
pprev=p;
qprev=q;
/*swapping for q in the place of p*/
temp=qcurr;
/*swapping for p in the place of q*/
temp=pcurr;
}```

2. [code]
Before
Code:
`A -> B -> ... L -> P -> R -> ... -> M -> Q -> S -> ...`
After
Code:
```
------------------------------
| ------------------         |
| |                |         |
| V                |         V
A -> B -> ... L  |-P    R -> ... -> M  - Q    S -> ...
|         ^              | ^
|         ---------------| |
|                          |
---------------------------```
So you need to change 4 pointers

Easier will be to swap contents of the P node and Q node living links intact...
Or - you need to pass M and L nodes the the swap function which will swap P and Q nodes (using 4 links method)

And special case will be when one of nodes is Head

3. A -> D -> ... C -> B -> E

4. Originally Posted by whiteflags
if you need to walk whole list for each simple operation on it - you are working with the wrong container type or your logic is broken

5. Originally Posted by Pulock2009
You went wrong in your second sentence:
the function should take 2node pointers as input parameters and exchange their place in the linked list
It needs three parameters, or four if the items are not consecutive.

6. Originally Posted by vart
if you need to walk whole list for each simple operation on it - you are working with the wrong container type or your logic is broken
Well we don't have the benefit of prev links in a singly linked list, so if you aren't going to pass in all the necessities, then you will have to walk the list to get prev nodes. It's not still broken now is it?

7. You can only need the two pointers if the list is circular. That's the only way you can get away with just passing the two nodes to swap. Otherwise, you at a bare minimum need a pointer to the root of the node. Not the node itself, a pointer to it -- in case it happens to be one of the ones you're trying to swap.

Quzah.

8. thanks a lot!!!

thanks a lot for all of your valuable advice. it was particularly enlightening for me to know that one needs to pass 4 parameters in case of a singly linked list and that my idea would be applicable for only circular linked lists. also i was thinking of swapping the node-data instead of the links which is what i will be doing now.