方法一 递归法
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
return merge(list1,list2);
}
ListNode *merge(ListNode *left,ListNode *right){
if(left==nullptr)
return right;
if(right==nullptr)
return left;
if(left->val<=right->val){
left->next=merge(left->next,right);
return left;
}
if(left->val>right->val){
right->next=merge(left,right->next);
return right;
}
return nullptr;
}
};
方法二 迭代法
双指针
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode *p=new ListNode(0);
ListNode *l1=list1,*l2=list2,*head=p,*tail=p;
while(l1&&l2){
if(l1->val<=l2->val){
tail->next=l1;
tail=l1;
l1=l1->next;
tail->next=NULL;
}else{
tail->next=l2;
tail=l2;
l2=l2->next;
tail->next=NULL;
}
}
tail->next=l1?l1:l2;
return p->next;
}
};