Constant space, simple iterative C++ solution


  • 0
    Y
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            ListNode dummy(0),*pre(&dummy),*left(nullptr),*right(nullptr);
            dummy.next = head;
            while(pre && pre->next && pre->next->next){
                left = pre->next;
                right = left->next;
                
                pre->next = right;
                left->next = right->next;
                right->next = left;
    
                pre = left;
            }
            return dummy.next;
        }
    };

Log in to reply
 

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