法一:使用一个额外的链表
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *head=new ListNode(-1);
ListNode *p=head;
while(l1&&l2){
if(l1->val<l2->val){
p->next=l1;
l1=l1->next;
}
else{
p->next=l2;
l2=l2->next;
}
p=p->next;
}
p->next=l1?l1:l2;
return head->next;
}
};
法二:不使用额外链表,递归
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(!l1) return l2;
if(!l2) return l1;
if(l1->val<l2->val){
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}
else{
l2->next=mergeTwoLists(l1,l2->next);
return l2;
}
}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(!l1) return l2;
if(!l2) return l1;
ListNode *head=l1->val<l2->val?l1:l2;
ListNode *p=l1->val<l2->val?l2:l1;
head->next=mergeTwoLists(head->next,p);
return head;
}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(!l1||(l2 && l1->val>l2->val )) swap(l1,l2);
if(l1) l1->next=mergeTwoLists(l1->next,l2);
return l1;
}
};