Very simple 3ms C++ solution


  • 1
    S

    Given at least 2 nodes

    • Stash a nextpair pointer to node #3 (possibly NULL)
    • Point head->next->next at head creating a 2 node loop
    • Point head at head->next - we still have a 2 node loop, except that head points to the other node in the pair
    • Break loop by pointing head->next->next at result of calling swap on nextpair
      ListNode* swapPairs(ListNode* head) {
        if (head && head->next) {
          ListNode *nextpair = head->next->next;
          head->next->next = head;
          head = head->next;
          head->next->next = swapPairs(nextpair);
        }
        return head;
      }
    

  • 0
    V

    @sameerp How does it works , can you plz explain?


Log in to reply
 

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