Skip to content

Commit a409297

Browse files
committed
merge k sorted lists
1 parent 388e17d commit a409297

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

merge-k-sorted-lists/se6816.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
class Solution {
3+
public ListNode mergeKLists(ListNode[] lists) {
4+
ListNode list= new ListNode(0); // head
5+
ListNode curr=list;
6+
PriorityQueue<ListNode> pq=new PriorityQueue<ListNode>((l1, l2)->{
7+
return l1.val - l2.val;
8+
});
9+
for(int i=0; i<lists.length;i++){
10+
if(lists[i]!=null){
11+
pq.offer(lists[i]);
12+
}
13+
}
14+
while(!pq.isEmpty()){
15+
ListNode temp = pq.poll();
16+
curr.next=new ListNode(temp.val);
17+
curr=curr.next;
18+
temp=temp.next;
19+
if(temp!=null){
20+
pq.offer(temp);
21+
}
22+
23+
}
24+
return list.next;
25+
26+
27+
}
28+
}

0 commit comments

Comments
 (0)