I found that, using a function will be better (60%+Faster) in c++!


  • 1
    Z
     ListNode* merge(ListNode* l1, ListNode* l2) 
        {
            ListNode* l = new ListNode(0);
            ListNode* current = l;
            ListNode* a = l1;
            ListNode* b = l2;
            while(a&&b)
                {
                    if(a->val < b->val)
                    {
                        current->next=a;
                        a=a->next;
                    }
                    else
                    {
                        current->next=b;
                        b=b->next;
                    }
                    current=current->next;
                }
                if(a)
                {
                    current->next=a;
                }
                else if(b)
                {
                    current->next=b;
                }
            return l->next;
        }
        
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 
        {
            if(!l1)return l2;
            if(!l2)return l1;
            else return merge(l1, l2);
        }

Log in to reply
 

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