递归
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if(!list1)return list2;
if(!list2)return list1;
if(list1->val>=list2->val){
list2->next=mergeTwoLists(list1,list2->next);
return list2;
}else{
list1->next=mergeTwoLists(list1->next,list2);
return list1;
}
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4e0c2381a98b76da8bd4415bfd81f487.png)
迭代
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if(!list1)return list2;
if(!list2)return list1;
auto list11=new ListNode();
list11->next=list1;
auto list1_pro=list11;
while(list1||list2){
if(list1&&list2){
if(list1->val>=list2->val){
list1_pro->next=list2;
list2=list2->next;
list1_pro=list1_pro->next;
list1_pro->next=list1;
}else{
list1=list1->next;
list1_pro=list1_pro->next;
}
}else if(!list1&&list2){
list1_pro->next=list2;
break;
}else if(list1&&!list2){
break;
}
}
return list11->next;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5ce4f0d351de45d43492c7d890782a80.png)