Time Cost

14min52s

Implementation

Quick-Slow Pointers. When the quick pointer hits the boundary then stops.

Code

  • Solution
    class Solution {
    public:
      ListNode* swapPairs(ListNode* head) {
          if (head == nullptr || head->next == nullptr) return head;
          // use two-pointers
          ListNode dummy(0);
          dummy.next = head;
    
          ListNode* fast = head->next;
          ListNode* slow = head;
          ListNode* prev = &dummy;
    
          while (fast) {
              ListNode* nxt = fast->next;
              prev->next = fast;
              fast->next = slow;
              slow->next = nxt;
              prev = slow;
              if (!nxt || !nxt->next) {
                  break;
              }
              slow = nxt;
              fast = nxt->next;
          }
    
          return dummy.next;
      }
    };