8ms cpp accepted solution


  • 0
    T
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
            //speed up
            if(NULL == l1) return l2;
            if(NULL == l2) return l1;
            ListNode res(0);
            ListNode *curRes = &res;
            while(l1 != NULL && l2 != NULL){
                if(l1->val < l2->val)
                {
                    curRes->next = l1;
                    l1 = l1->next;
                }else
                {
                    curRes->next = l2;
                    l2 = l2->next;
                }
                curRes = curRes->next;
            }
            curRes->next = l1 ? l1 : l2;
            return res.next;
        }

  • 0
    T

    12ms recursive solution

    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
            if(NULL == l1) return l2;
            if(NULL == l2) return l1;
            if(l1->val > l2->val) swap(l1, l2);
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        }

Log in to reply
 

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