C++ solution Easy to understand with comments and explanations.


  • 4
    K

    Renewed Solution

    The main point is that if there are 2 more nodes (which is a pair) following, then swap them, otherwise, end the process.

    bool SwapHelper(ListNode *p)
    {
        if (p->next and p->next->next)
        {
            ListNode *n1 = p->next;
            ListNode *n2 = p->next->next;
            
            p->next = n2;
            n1->next = n2->next;
            n2->next = n1;
            
            return true;
        }
        
        return false;
    }
    
    ListNode *swapPairs(ListNode *head) 
    {
        if (!head) 
            return nullptr;
        
        // Create a head Node
        ListNode new_head(-1);
        new_head.next = head;
        
        ListNode *p = &new_head;
        
        // While has two more node and swap succeeded
        while (SwapHelper(p)) 
            p = p->next->next;
        
        return new_head.next;
    }

  • 0
    L

    very readable and easy to get. The addition of the head node is a blight point of the solution.


  • 0
    A

    very easy to understand!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.