Swapping nodes in a linked list

前端 未结 5 1549
逝去的感伤
逝去的感伤 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:56

    Four easy options:

    First option: Keep track of the pointer to prev (probably the direction the assignment is expected to take).

    Second option: Implement a doubly linked list so that you can always find the previous node.

    Third option: Implement a singly linked list (as your assignment probably calls for), but give each node two pointers: One pointing to 'next', and one pointing to the data payload (which could be just about anything; a struct, an array, or a plain old data type). Then you just swap where the payload pointers point without worrying about 'next' and 'prev'.

    A fourth option: Swap the data itself (possibly the direction the assignment is expected to take).

    There are use cases for each of the above.

提交回复
热议问题