Merge Sort Solution C++


  • 0
    S

    class Solution {
    public:

    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        
        ListNode *new_list;
        ListNode *dummy = new ListNode(0);
        new_list = dummy;
        
        while(l1 && l2){
            
            if(l1->val < l2->val){
               new_list->next =  new ListNode(l1->val);
               new_list = new_list->next;
               l1 = l1->next;
            }
            else {
               new_list->next =  new ListNode(l2->val);
               new_list = new_list->next;
               l2 = l2->next;
            }
            
        }
        while(l1){
            new_list->next =  new ListNode(l1->val);
            new_list = new_list->next;
            l1 = l1->next;
        }
        while(l2){
            new_list->next =  new ListNode(l2->val);
            new_list = new_list->next;
            l2 = l2->next;
        }
        return dummy->next;
    }
    

    };


Log in to reply
 

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