- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem23.java
More file actions
Latest commit
78 lines (67 loc) · 1.55 KB
/
Copy pathProblem23.java
File metadata and controls
78 lines (67 loc) · 1.55 KB
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
publicclassProblem23 {
publicstaticvoidmain(String[] args) {
ListNodea = newListNode(1);
a.next = newListNode(4);
a.next.next = newListNode(5);
ListNodeb = newListNode(0);
b.next = newListNode(3);
b.next.next = newListNode(4);
ListNodec = newListNode(2);
c.next = newListNode(6);
ListNode[] lists = newListNode[]{a, b, c};
ListNoderes = newProblem23().mergeKLists(lists);
ListNodep = res;
for (; p.next != null ; p=p.next) {
System.out.print(p.val + "->");
}
System.out.print(p.val);
}
publicListNodemergeKLists(ListNode[] lists) {
intinterval = 1;
while (interval < lists.length) {
for(inti = 0; i < lists.length - interval; i += interval * 2) {
lists[i] = merge2Lists(lists[i], lists[interval + i]);
}
interval *= 2;
}
returnlists[0];
}
// merge 2 lists
ListNodemerge2Lists(ListNodel1, ListNodel2) {
ListNodep = l1;
ListNodeq = l2;
ListNodepre = null;
while (p!= null && q != null) {
if(q.val < p.val) {
// insert q before p
ListNodetmp = 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;
}
}
returnl1;
}
}
classListNode {
intval;
ListNodenext;
ListNode(intx) { val = x; }
}