Swapping adjacent elements of linked list

前端 未结 4 600
执念已碎
执念已碎 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:25

    With no recursion:

    void swap(node **head)
    {
        while (*head && (*head)->next)
        {
            node* tmp = *head;
            *head = tmp->next;
            tmp->next = (*head)->next;
            (*head)->next = tmp;
            head = &tmp->next;
        }
    }
    

    Invoke swap( & list_head_ptr).


    Alternatively, you can pass the head pointer by reference-to-pointer and utilize a local pointer-to-pointer member:

    void swap(node*& head)
    {
        node **pp = &head;
        while (*pp && (*pp)->next)
        {
            node* tmp = *pp;
            *pp = tmp->next;
            tmp->next = (*pp)->next;
            (*pp)->next = tmp;
            pp = &tmp->next;
        }
    }
    

    and invoke as swap(list_head_ptr). Either method works.

提交回复
热议问题