Share My Code C++ Using the Dummy Head 9ms Easy to Understand


  • 0
    /**
    * 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 head(0);
    		ListNode* res = &head;
    		ListNode* p = res;
    
    		while (l1&&l2)
    		{
    			if (l1->val < l2->val)
    			{
    				p->next = l1;
    				l1 = l1->next;
    			}
    			else
    			{
    				p->next = l2;
    				l2 = l2->next;
    			}
    			p = p->next;
    		}
    		p->next = l1 ? l1 : l2;
    		return res->next;
    	}
    };
    

Log in to reply
 

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