# My 8ms C++ iterative answer

• ``````ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
// bounday situations
if(!l1&&!l2) return l1;
if(!l1||!l2) return (l1==nullptr?l2:l1);
//general situations
ListNode* pre;
ListNode* res;
//initialize the pre pointer
if(l1->val<l2->val){
pre = l1;
l1 = l1->next;
}else{
pre= l2;
l2 = l2->next;
}
res = pre;

//sort, merge
while(l1!=nullptr || l2!=nullptr){
if(l2==nullptr&&l1!=nullptr){
while(l1!=nullptr){
pre->next = l1;
pre= pre->next;
l1 = l1->next;
}

}else if(l1==nullptr &&l2!=nullptr){
while(l2!=nullptr){
pre->next = l2;
pre= pre->next;
l2 = l2->next;
}

}else{
if(l1->val < l2->val){
pre->next =l1;
pre= pre->next;
l1 = l1->next;
}
else{
pre->next = l2;
pre= pre->next;
l2=l2->next;
}
}
}
return res;
}``````

• //My solotion 0 is null

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

if (pre!=0){
pre->next=l2;
}else{
}
pre=l2;
l2=l2->next;
}
}

if (l1 == 0){
pre->next = l2;
}

if (l2 == 0){
pre->next=l1;
}