Easy 12ms C++ solution


  • 2
    X
    class Solution {
    public:
        ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
            ListNode head(0);
            ListNode* iter = &head;
            while(l1 && l2) {
                if(l1->val < l2->val) {
                    iter->next = l1;
                    l1 = l1->next;
                } else {
                    iter->next = l2;
                    l2 = l2 -> next;
                }
                iter = iter->next;
            }
            iter->next = l1 ? l1 : l2;
            return head.next;
        }
    };

  • 0
    R

    I ended up doing something similar, getting 12 ms as well.

    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 
    {
        ListNode dummy(0);
        ListNode* node = &dummy;
        
        while(l1 && l2)
        {
            ListNode*& next = (l1->val < l2->val)  ? l1 : l2;
            node->next=next;
            node = next;
            next = next->next;
        }
        
        node->next = l1 ? l1 : l2;
        
        return dummy.next;   
    }

Log in to reply
 

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