My simple recursive C++ solution in 6 lines(4ms)


  • 6
    6
    ListNode* swapPairs(ListNode* head) {
        if (head == NULL) { return NULL; }
        if (head ->next == NULL) { return head; }
        
        ListNode *newHead = head->next;
        head->next = swapPairs(head->next->next);
        newHead->next = head;
        return newHead;
    }

  • 4
    S

    you can replace the first two sentence with "if (!head || !(head->next) ) return head;"


Log in to reply
 

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