Accepted basic C++ solution 8ms


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

    };


  • 0
    0

    It is a bad solution.
    Firstly, you didn't take the descending order into consideration.
    Secondly, you change the original lists l1 and l2.
    Thirdly, you didn't release the heap space that you applied.


  • 1
    J

    You need not new a new node,
    If you must do this , you should delete the node to avoid memory leak.

    The following is my code, it works well, and it is simlar to yours but not new new node.

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

  • 0
    B

    As 09122389 says, you forget to delete the node you newed.


Log in to reply
 

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