Swapping adjacent elements of linked list

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

    In fact it is enough to swap only the data members of nodes. There is no need to swap the pointers themselves.

    Nevertheless if to use your approach then the function can look like

    void SwapList( node *head )
    {
        if ( head != nullptr && head->next != nullptr )
        {
            node *next = head->next;
            std::swap( *head, *next );
            std::swap( head->next, next->next );
    
            SwapList( head->next->next );
        }
    }
    

    Here is a demonstrative program

    #include 
    #include 
    
    struct node
    {
        int value;
        node *next;
    };
    
    node * AddNode( node *head, int value )
    {
        head = new node { value, head };
    
        return head;
    }
    
    void PrintList( node *head )
    {
        for ( ; head != nullptr; head = head->next )
        {
            std::cout << head->value << ' ';
        }
    }
    
    void SwapList( node *head )
    {
        if ( head != nullptr && head->next != nullptr )
        {
            node *next = head->next;
            std::swap( *head, *next );
            std::swap( head->next, next->next );
    
            SwapList( head->next->next );
        }
    }
    
    int main() 
    {
        node *head = nullptr;
    
        for ( int i = 10; i != 0; )
        {
            head = AddNode( head, --i );
        }
    
        PrintList( head );
        std::cout << std::endl;
    
        SwapList( head );
    
        PrintList( head );
        std::cout << std::endl;
    
        return 0;
    }
    

    The output is

    0 1 2 3 4 5 6 7 8 9 
    1 0 3 2 5 4 7 6 9 8 
    

    You can use the shown function as a template (or base) for your function.

提交回复
热议问题