My C++ solution using recursive loop


  • 0
    T
    
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
        {
            if(l1 == NULL)
                return l2;
    
            if(l2 == NULL)
                return l1;
    
            if(l1->val < l2->val)
            {
                ListNode* t1 = l1;
    
                while(t1 != NULL && t1->next != NULL && t1->next->val < l2->val)
                {
                    t1 = t1->next;
                }
    
                t1->next = mergeTwoLists(t1->next,l2);
                return l1;
            }
            else
            {
                ListNode* t2 = l2;
    
                while(t2 != NULL && t2->next != NULL && t2->next->val < l1->val)
                {
                    t2 = t2->next;
                }
    
                t2->next = mergeTwoLists(l1, t2->next);
                return l2;
            }
        }
    

  • 0
    T

    A shorter version but with low performance:

    ListNode* mergeTwoLists2(ListNode* l1, ListNode* l2)
            {
                if(l1 == NULL)
                    return l2;
    
                if(l2 == NULL)
                    return l1;
    
                if(l1->val < l2->val)
                {
                    ListNode* t1 = l1;
                    t1 = t1->next;
                    l1->next = mergeTwoLists2(t1,l2);
                    return l1;
                }
                else
                {
                    ListNode* t2 = l2;
                    t2 = t2->next;
                    l2->next = mergeTwoLists2(l1, t2);
                    return l2;
                }
            }
    

Log in to reply
 

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