forked from architsingla13/InterviewBit-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeKSortedLists.java
More file actions
54 lines (41 loc) · 1020 Bytes
/
MergeKSortedLists.java
File metadata and controls
54 lines (41 loc) · 1020 Bytes
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
package Heaps;
import java.util.ArrayList;
import java.util.PriorityQueue;
/**
* Author - archit.s
* Date - 01/11/18
* Time - 12:09 PM
*/
public class MergeKSortedLists {
class ListNode {
public int val;
public ListNode next;
ListNode(int x) { val = x; next = null; }
}
public ListNode mergeKLists(ArrayList<ListNode> a) {
ListNode head = null;
ListNode last = null;
PriorityQueue<ListNode> p = new PriorityQueue<>((x, y) -> x.val - y.val);
for(ListNode t: a){
if(t!=null){
p.offer(t);
}
}
while(p.size()>0){
ListNode t = p.poll();
if(t.next!=null){
p.offer(t.next);
}
if(head == null){
head = t;
last = t;
}
else{
last.next = t;
last = last.next;
}
}
last.next = null;
return head;
}
}