Simple C++ 3ms solution


  • 0
        ListNode* swapPairs(ListNode* head) {
            if(!head || !head->next) return head;
            ListNode res(0);
            ListNode *pre = &res, *one = head, *two = head->next;
            while(one && two){
                one->next = two->next;
                two->next = one;
                pre->next = two;
                pre = one;
                one = one->next;
                if(one) two = one->next;
            }
            return res.next;
        }
    

Log in to reply
 

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