Simple non-recursive c++ solution


  • 0
    R

    ListNode* swapPairs(ListNode* head) {

        auto slow = head;
        auto prev = &head;
    
        while (slow && slow->next) {
            auto fast = slow->next;
            auto next = fast->next;
            *prev = fast;
            fast->next = slow;
            slow->next = next;
            prev = &slow->next;
            slow = next;
        }
    
        return head;
    

    }


Log in to reply
 

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