将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
这个最方便的就是递归:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;
ListNode temp;
if (l1.val < l2.val) {
temp = l1;
temp.next = mergeTwoLists(l1.next, l2);
} else {
temp = l2;
temp.next = mergeTwoLists(l1, l2.next);
}
return temp;
}
测试:
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(3);
ListNode l4 = new ListNode(4);
ListNode l5 = new ListNode(5);
l1.next = l3;
l2.next = l4;
l3.next = l5;
MergeTwoLists mt = new MergeTwoLists();
ListNode result = mt.mergeTwoLists(l1,l2);
System.out.println(result.next.val);
}