4 Lines in C++ Using Recursion with no extra space

  • 1
    ListNode* swapPairs(ListNode* head) {
            if(head == NULL || head->next == NULL) return head;
            swap(head->val, head->next->val);
            head->next->next = swapPairs(head->next->next);
            return head;

  • 1

    You cannot modify the values in the list, only nodes itself can be changed.

Log in to reply

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