LeetCode21-合并两个有序链表

LeetCode21-合并两个有序链表

递归实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
} else if (list2 == null) {
return list1;
}

if (list1.val < list2.val) {
ListNode res = mergeTwoLists(list1.next, list2);
list1.next = res;
return list1;
} else {
ListNode res = mergeTwoLists(list1, list2.next);
list2.next = res;
return list2;
}

}