# Accepted basic C++ solution 8ms

• ``````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;
}
``````

};

• 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.

• 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;

if(l1->val <= l2->val) {
l1 = l1->next;
} else {
l2 = l2->next;
}

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;