Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
代码:
递归版:
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head=new ListNode(0);
if(l1!=null&&l2!=null){
if(l2.val<l1.val){
ListNode temp=l1;
l1=l2;
l2=temp;
}
head=head.next=l1;
head.next=mergeTwoLists(l1.next,l2);
return head;
}
else if(l1==null)
return l2;
else
return l1;
}
}
非递归版:
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head=new ListNode(0);
ListNode cur=head;
ListNode temp=null;
while(l1!=null&&l2!=null){
if(l2.val<l1.val){
temp=l1;
l1=l2;
l2=temp;
}
cur=cur.next=l1;
l1=l1.next;
}
while(l1!=null){
cur=cur.next=l1;
l1=l1.next;
}
while(l2!=null){
cur=cur.next=l2;
l2=l2.next;
}
return head.next;
}
}