public class MergeTwoList {
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode result = null;
// 如果l1和l2有一个为null,返回另一个
if (l1 == null) return l2;
if (l2 == null) return l1;
// 如果l1的值小于l2的值,l1为头节点,开始递归
if (l1.val < l2.val) {
result = l1;
l1.next = mergeTwoLists(l1.next, l2);
} else {
result = l2;
l2.next = mergeTwoLists(l2.next, l1);
}
return result;
}
}