My two 8ms C++ solutions


  • 0
    J

    Solution 1:

    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            if (!l1) return l2;
            if (!l2) return l1;
            ListNode *head, *cur;
            if (l1->val < l2->val)
            {
                head=l1;
                l1 = l1->next;
            }
            else
            {
                head = l2;
                l2 = l2->next;
            }
            cur = head;
            while (l1 && l2)
            {
                if (l1->val < l2->val)
                {
                    cur->next = l1;
                    l1 = l1->next;
                }
                else
                {
                    cur->next = l2;
                    l2 = l2->next;
                }
                cur = cur->next;
            }
            if (!l2) cur->next = l1;
            else cur->next = l2;
            return head;
        }
    };
    

    Solution 2:

    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            if (!l1) return l2;
            if (!l2) return l1;
            ListNode *head, *nex;
            if (l1->val < l2->val)
            {
                head=l1;
                nex = l1->next;
    
                while (nex && l2)
                {
                    if (nex->val < l2->val)
                    {
                        l1 = nex;
                        nex = nex->next;
                    }
                    else
                    {
                        l1->next = l2;
                        l1 = l1->next;
                        l2 = l2->next;
                        l1->next = nex;
                    }
                }
                if (!nex) l1->next = l2;
            }
            else
            {
                head = l2;
                nex = l2->next;
    
                while (nex && l1)
                {
                    if (nex->val < l1->val)
                    {
                        l2 = nex;
                        nex = nex->next;
                    }
                    else
                    {
                        l2->next = l1;
                        l2 = l2->next;
                        l1 = l1->next;
                        l2->next = nex;
                    }
                }
                if (!nex) l2->next = l1;
            }
            return head;
        }
    };

Log in to reply
 

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