I wrote a function that swaps two consecutive nodes, but then I realized quite a few problems:
1.) The nodes may not be adjacent to each other
2.) The nodes may be the first or last nodes in the list
3.) The nodes may be out of order (I assume the first one comes before the second one, but the user may pass them in reverse order)
Of course, I can fix all these problems in my code, but that would seem like way too complicated of a code....it seems very inefficient.
I don't see any way to avoid having to cater to all these special cases. Is there a better way to swap nodes?
I'm not looking for any code, just for some conceptual help.
You can remove a node A from the list, but you must remember its position. You can insert node A next to node B. Then you can remove B and insert it to A's original position. This only requires sane find(), insert() and remove().
Actually, them being consecutive might be the a special case.
With correct algorithm you actually need only to check for (2) case
Works with all your cases, handles self-swapping and consecutive nodes.
Rightmost uses std::swap