Jack Li's Blog

0024. Swap nodes by pairs

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        // 1 2 3 4
        // s f
        ListNode* dummy = new ListNode();
        dummy->next = head;

        ListNode* fast = dummy;
        ListNode* slow = dummy;
        ListNode* before = dummy;

        while(fast->next != nullptr && fast->next->next != nullptr) {
            fast = fast->next->next;
            slow = slow->next;

            // swap fast and slow
            // dummy -> 1 -> 2 -> 3 -> 4
            // b.    .  s.   f.   n
            ListNode* next = fast->next;
            fast->next = slow;
            slow->next = next;
            before->next = fast;
            fast = slow;
            before = slow;
        }

        return dummy->next;
    }
};