C++
非递归,每次选择两者中较小的,和数组合并类似
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(!l1)
return l2;
if(!l2)
return l1;
ListNode* head=new ListNode(0);
ListNode* Merge=new ListNode(0);
head=Merge;
while(l1&&l2){
if(l1->val>l2->val){
Merge->next=l2;
l2=l2->next;
}else{
Merge->next=l1;
l1=l1->next;
}
Merge=Merge->next;
}
if(!l1&&l2){
Merge->next=l2;
}
if(l1&&!l2){
Merge->next=l1;
}
head=head->next;
return head;
}
递归:
每次返回当次比较中较小的,递归比较list 的 next和未选中List中的较小的作为合并的返回next
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(!l1)
return l2;
if(!l2)
return l1;
ListNode* res=new ListNode(0);
if(l1->val < l2->val) {
res=l1;
res->next=mergeTwoLists(l1->next,l2);
}else{
res=l2;
res->next=mergeTwoLists(l1,l2->next);
}
return res;
}
Java
非递归
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
ListNode head=new ListNode(0);
ListNode res=head;
while(l1!=null && l2!=null){
if(l1.val<l2.val){
head.next=l1;
l1=l1.next;
}else{
head.next=l2;
l2=l2.next;
}
head=head.next;
}
if(l1!=null && l2==null)
head.next=l1;
if(l1==null && l2!=null)
head.next=l2;
res=res.next;
return res;
}
递归
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
ListNode head=new ListNode(0);
if(l1.val<l2.val){
head=l1;
head.next=mergeTwoLists(l1.next,l2);
}else{
head=l2;
head.next=mergeTwoLists(l1,l2.next);
}
return head;
}