Swapping nodes in a linked list

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

    Simple way to swap to node... I am not writing actual code. I am just giving you a hint to swap nodes.

    [1]->[2]->[3]->[4]
    

    Suppose this is your linked list and you want to swap [2] and [3].

    1. use loop to reach till [2]. so your temp is at [2].
    2. Now temp1 = temp->next; Hence temp1 is at [3].
    3. temp->next = temp1->next;

      temp1->next = temp;

    so now temp->next = [4] and temp1->next = [2]

提交回复
热议问题