3ms C++ solution


  • 0
    Y
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            if(!head || !head->next) return head;
            ListNode dummy(0),*pre(&dummy),*left(nullptr),*right(nullptr);
            dummy.next = head;
            while(pre->next && pre->next->next){
                left = pre->next;
                right = pre->next->next;
                //begin to swap 
                left->next = right->next;
                pre->next = right;
                right->next = left;
    
                //prepare for next swap
                pre = pre->next->next;
            }
            return dummy.next;
        }
    };
    

Log in to reply
 

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