Swapping nodes in a linked list

前端 未结 5 1520
逝去的感伤
逝去的感伤 2020-12-20 06:04

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

5条回答
  •  隐瞒了意图╮
    2020-12-20 06:55

    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;
    

提交回复
热议问题