Question:
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.
本题难度easy,关键在于别想复杂了。题目是有assumption的:sort都是从小到大。下面提供两个解法:
一、常规
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//require
ListNode fake=new ListNode(0);
ListNode cur=fake;
//invariant
while(true){
if(l1==null){cur.next=l2;break;}
if(l2==null){cur.next=l1;break;}
if(l1.val>l2.val){
cur.next=l2;
l2=l2.next;
}else{
cur.next=l1;
l1=l1.next;
}
cur=cur.next;
}
//ensure
return fake.next;
}
}
二、recursion
递归方法是在disuss上看到的,原文:Java, 1 ms, 4 lines codes, using recursion
(依然是为华人写的,再次展现中国人在算法方面的才华)
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}