题解 | #合并两个排序的链表#
合并两个排序的链表
http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
众猿周知,万物皆可递归
public ListNode Merge(ListNode l1,ListNode l2) {
if (l1 == null || l2 == null) return l2 == null ? l1 : l2;
ListNode head = (l1.val<=l2.val) ? l1 : l2;
head.next = Merge(head.next,head == l1 ? l2 : l1);
return head;
}
众猿亦知,可递归就可迭代
public ListNode Merge(ListNode l1, ListNode l2) {
ListNode dum = new ListNode(0);
ListNode cur = dum;
while (l1!=null&&l2!=null){
if (l1.val<=l2.val) {
cur.next = l1;
l1 = l1.next;
}else{
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if (l1==null) cur.next = l2;
if (l2==null) cur.next = l1;
return dum.next;
}