LC 24. Swap Nodes in Pairs

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(!head || !head->next)
            return head;
        ListNode* prev = head;
        ListNode* next = head->next;
        
        while(next->next && next->next->next){
            cout << prev->val << " " << next->val;
            swap(prev->val,next->val);
            prev = prev->next->next;
            next = prev->next;
            cout << prev->val << " " << next->val;
        }
        swap(prev->val,next->val);
        return head;
    }
};


Dicussion Forum