Solution in C++


  • 1
    P
    class Solution 
    {
    public:
    	ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 
    	{
    		ListNode* head = new ListNode(0), *p = head;
    		while (NULL != l1 && NULL != l2) 
    		{
    			if (l1->val < l2->val) { p->next = l1; l1 = l1->next; }
    			else { p->next = l2; l2 = l2->next; }
    			p = p->next;
    		}
    		if (NULL == l1) p->next = l2;
    		else p->next = l1;
    		p = head;
    		head = head->next;
    		delete p;
    		return head;
    	}
    };

Log in to reply
 

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