My C++ solution 12ms


  • 0
    C

    After completing I have seen better solutions, but anyway here it is....

    class Solution {
    public:
        ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
            ListNode* res = new ListNode(-1); // dummy
            ListNode* r = res;
            while (l1 || l2) {
                while (l1 && (!l2 || l1->val <= l2->val)) {
                    r->next = new ListNode(l1->val);
                    r = r->next;
                    l1 = l1->next;
                }
                while (l2 && (!l1 || l2->val <= l1->val)) {
                    r->next = new ListNode(l2->val);
                    r = r->next;
                    l2 = l2->next;
                }
            }
            return res->next;
        }
    };

  • 3
    B

    A similar one;

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

  • 0
    C

    More concise than mine. Great !


  • 2
    M
    enter code heclass Solution {
    

    public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {

    ListNode *res=new ListNode(0), *tmp=res;
    res->next=NULL;
    
    while(l1&&l2)
    {
        if(l1->val<l2->val)
        {
            res->next=l1;
            res=res->next;
            l1=l1->next;
        }
        
        else
        {
            res->next=l2;
            res = res->next;
            l2=l2->next;
        }
    }
    
    if(l1)
    res->next=l1;
    
    else
    res->next=l2;
    
    return tmp->next;
    

    }


  • 0
    L

    memory leak!!
    ListNode head(-1);
    ListNode* res = &head;

    maybe better


  • 0
    C

    yeah thanks for spotting!


  • 0
    L

    Does it cause memory leak?


Log in to reply
 

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