5 lines, 4ms, c++, recursion solution, self-explained code


  • 0
    T
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL || head->next == NULL) return head;
        
        ListNode* rest = swapPairs(head->next->next), *oldfirst = head, *oldsecond = head->next;
        
        oldsecond->next = oldfirst;
        oldfirst->next = rest;
        
        return oldsecond;
    }

Log in to reply
 

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