Solution in 12ms C++


  • 0
    P
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    
        if(l1 == NULL && l2 == NULL)
    	    return NULL;
    
    	ListNode * tmpl1 = l1;
    	ListNode * tmpl2 = l2;
    
    	ListNode * firstNode = new ListNode(0);
    	ListNode * currSortedNode = firstNode;
    
    	while(tmpl1 != NULL && tmpl2 != NULL)
    	{
    		if(tmpl1->val <= tmpl2->val)
    		{
    			ListNode * newNode = new ListNode(tmpl1->val);
    			currSortedNode->next = newNode;
    			currSortedNode = newNode;
    			tmpl1 = tmpl1->next;
    		}
    		else
    		{
    			ListNode * newNode = new ListNode(tmpl2->val);
    			currSortedNode->next = newNode;
    			currSortedNode = newNode;
    			tmpl2 = tmpl2->next;
    		}
    	}
    
    	while(tmpl1 != NULL)
    	{
    		ListNode * newNode = new ListNode(tmpl1->val);
    		currSortedNode->next = newNode;
    		currSortedNode = newNode;
    		tmpl1 = tmpl1->next;
    	}
    
    	while(tmpl2 != NULL)
    	{
    		ListNode * newNode = new ListNode(tmpl2->val);
    		currSortedNode->next = newNode;
    		currSortedNode = newNode;
    		tmpl2 = tmpl2->next;
    	}
    
    	ListNode * sortedHead = firstNode->next;
    	delete firstNode;
    
    	return sortedHead;
    }

Log in to reply
 

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