Swapping adjacent elements of linked list

前端 未结 4 602
执念已碎
执念已碎 2021-01-16 09:50

The below is my code to recursive swap the adjacent elements of a linked list. I am losing the pointer to every second element after the swap. The input is 1->2->3->4->5->6-

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-16 10:27

    Using recursion:

    void nodelist::swap(node** head) {
      if (!*head || !(*head)->next) return;
      node* const sw = (*head)->next;
      (*head)->next = sw->next;
      sw->next = *head;
      *head = sw;
      swap(&(sw->next->next));
    }
    

提交回复
热议问题