I am trying to swap two adjacent nodes in a linked list, and I think I understand the idea of how to do it using a temporary node.
Here is my struct swap function
With data this small, you might as well just swap everything but the next
pointers:
partType tmp = *item;
memcpy(item, item->next, offsetof(item, next));
memcpy(item->next, &tmp, offsetof(item, next));
If your data gets too large to do this, you'll need a pointer to the node before the two you want. The nice part is that your fixing of prev
's next
pointer acts as a temp variable, letting you not need one.
prev->next = item->next;
item->next = item->next->next;
prev->next->next = item;