-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem23.java
78 lines (67 loc) · 1.55 KB
/
Problem23.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
public class Problem23 {
public static void main(String[] args) {
ListNode a = new ListNode(1);
a.next = new ListNode(4);
a.next.next = new ListNode(5);
ListNode b = new ListNode(0);
b.next = new ListNode(3);
b.next.next = new ListNode(4);
ListNode c = new ListNode(2);
c.next = new ListNode(6);
ListNode[] lists = new ListNode[]{a, b, c};
ListNode res = new Problem23().mergeKLists(lists);
ListNode p = res;
for (; p.next != null ; p=p.next) {
System.out.print(p.val + "->");
}
System.out.print(p.val);
}
public ListNode mergeKLists(ListNode[] lists) {
int interval = 1;
while (interval < lists.length) {
for(int i = 0; i < lists.length - interval; i += interval * 2) {
lists[i] = merge2Lists(lists[i], lists[interval + i]);
}
interval *= 2;
}
return lists[0];
}
// merge 2 lists
ListNode merge2Lists(ListNode l1, ListNode l2) {
ListNode p = l1;
ListNode q = l2;
ListNode pre = null;
while (p!= null && q != null) {
if(q.val < p.val) {
// insert q before p
ListNode tmp = q.next;
if (pre != null) {
pre.next = q;
pre = q;
}
else {
pre = q;
l1 = pre;
}
pre.next = p;
q=tmp;
} else {
pre = p;
p = p.next;
}
}
if (p == null) {
if (pre != null) {
pre.next = q;
} else {
pre = q; l1 =pre;
}
}
return l1;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}