My solution in C++,not return a new list,but l1 or l2.


  • 0
    Z
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    		if (l1 == NULL) return l2;
    		if (l2 == NULL) return l1;
    		ListNode* p1 = l1->val <= l2->val ? l1 : l2;
    		ListNode* p2 = l1->val > l2->val ? l1 : l2;
    		ListNode* q1 = p1;
    		ListNode* q2 = p2;
    		while (p1 && p2)
    		{
    			if (p1->val <= p2->val)
    			{
    				q1 = p1;
    				p1 = p1->next;
    			}
    			else
    			{
    				q2 = p2->next;
    				p2->next = q1->next;
    				q1->next = p2;
    				q1 = q1->next;
    				p2 = q2;
    			}
    		}
    		if (p2)
    			q1->next = p2;
    		return l1->val <= l2->val ? l1 : l2;
    	}
    };

Log in to reply
 

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