C++ solution -- no recursion -- clean and concise


  • 0
    N
    ListNode* swapPairs(ListNode* head) {
            ListNode * dummy = new ListNode(0);
            dummy->next = head;
            
            ListNode * curr = dummy;
            
            while(curr&&curr->next&&curr->next->next)
            {
                ListNode* first = curr->next;
                ListNode* second = first->next;
                
                // adjust first and second "next" fields
                first->next = second->next;
                second->next = first;
                
                // curr should now point to second
                curr->next = second;
                
                // Jump 2 steps
                curr = first;
            }
            
            return dummy->next;
        }
    

Log in to reply
 

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