# My C++ solution 12ms

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

• A similar one;

``````class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
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;
}
}
};``````

• More concise than mine. Great !

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

}

• memory leak!!