My C++ Solution


  • 0
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            if ( l1 && !l2) return l1;
    		if (!l1 &&  l2) return l2;
    		if (!l1 && !12) return nullptr;
    		ListNode* head = new ListNode(0);
    		ListNode* rear = head;
    		while (l1 && l2){
    			if (l1->val <= l2->val){
    				ListNode* temp = new ListNode(l1->val);
    				rear->next = temp;
    				rear = temp;
    				l1 = l1->next;
    			}
    			else{
    				ListNode* temp = new ListNode(l2->val);
    				rear->next = temp;
    				rear = temp;
    				l2 = l2->next;
    			}
    		}
    		if (!l1 &&  l2) rear->next = l2;
    		if ( l1 && !l2) rear->next = l1;
    		return head->next;
        }
    };

Log in to reply
 

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