based on Merge 2 sorted lists.

1
2
3
4
5
6
7
8
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/

可以由k = (n+1)/2和后面的n = k看出这种辗转对半缩短的方法, (n+1)/2这种选择是非常重要的; (n+1)/2这种, n增加1之后会确实进1, i.e. n=0时对应的链表是lists[0]lists[n/2],n=1时是lists[1]lists[n/2 + 1], 这样合并的链表就确实成对地变化; 如果时n/2就不行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0) return null;
int n = lists.length;
int k = 0;
while (n > 1) {
k = (n + 1) / 2;
for (int i = 0; i < n / 2; ++i) {
lists[i] = mergeTwoLists(lists[i], lists[i + k]);
}
n= k;
}
return lists[0];
}

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0), cur = dummy;
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;
}
cur.next = l1 != null ? l1 : l2;
return dummy.next;
}
}