-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortKSortedList.java
More file actions
49 lines (40 loc) · 1.18 KB
/
SortKSortedList.java
File metadata and controls
49 lines (40 loc) · 1.18 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
package DoublyLinkedList;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* One of the important and hard questions!
*/
public class SortKSortedList {
public static Node sortedDll(Node head, int k) {
if (head == null) return head;
PriorityQueue<Node> pq = new PriorityQueue<>(new MyComparator());
Node newHead = null, last = null;
for (int i = 0; head != null && i <= k; i++) {
pq.add(head);
head = head.next;
}
while (!pq.isEmpty()) {
if (newHead == null) {
newHead = pq.peek();
newHead.prev = null;
last = newHead;
} else {
last.next = pq.peek();
pq.peek().prev = last;
last = pq.peek();
}
pq.poll();
if (head != null) {
pq.add(head);
head = head.next;
}
}
if (last != null) last.next = null;
return newHead;
}
static class MyComparator implements Comparator<Node> {
public int compare(Node n1, Node n2) {
return n1.data - n2.data;
}
}
}