Swap Nodes in Pairs

Key: how to advance 3 pointers in a sequence

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == nullptr || head->next == nullptr) return head;

        ListNode dummy(-1);
        dummy.next = head;
        ListNode *prev = &dummy;
        ListNode *cur = head;
        ListNode *ad = head->next;

        while (ad) {
            // swap
            cur->next = ad->next;
            prev->next = ad;
            ad->next = cur;

            // advance 
            prev = cur;
            cur = cur->next;
            // key!!!!! first update cur, then update ad based on new cur
            ad = cur != nullptr ? cur->next : nullptr;
        }

        return dummy.next;
    }
};

results matching ""

    No results matching ""