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.
My code:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2==null) return l1;
ListNode head;
if(l1.val<l2.val){
head = l1;
l1=l1.next;
}
else{
head = l2;
l2=l2.next;
}
ListNode cur = head;
while(l1!=null||l2!=null){
if(l1!=null&&l2!=null){
if (l1.val>l2.val){
cur.next = l2;
cur = cur.next;
l2 = l2.next;
}
else{
cur.next = l1;
cur = cur.next;
l1=l1.next;
}
}
if(l1==null){
cur.next = l2;
break;
}
if(l2==null){
cur.next = l1;
break;
}
}
return head;
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2==null) return l1;
ListNode head;
if(l1.val<l2.val){
head = l1;
head.next = mergeTwoLists(l1.next, l2);
}
else{
head = l2;
head.next =mergeTwoLists(l1,l2.next);
}
return head;
}
总结:要想着子问题,能不能用recursive method,会简单很多。