Skip to content

Commit 2a603d4

Browse files
Merge pull request #596 from Aarush2k1/patch-1
Leetcode 23: Merge k sorted linked lists
2 parents e814ec1 + b550f7f commit 2a603d4

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Java/Leetcode/Leetcode23.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/*
2+
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
3+
Merge all the linked-lists into one sorted linked-list and return it.
4+
Input: lists = [[1,4,5],[1,3,4],[2,6]]
5+
Output: [1,1,2,3,4,4,5,6]
6+
*/
7+
class Solution {
8+
public ListNode mergeKLists(ListNode[] lists) {
9+
PriorityQueue<ListNode> q=new PriorityQueue<>((a,b)->a.val-b.val);
10+
ListNode curr=new ListNode(0);
11+
ListNode ans=curr;
12+
13+
for(ListNode l:lists){
14+
while(l!=null){
15+
q.offer(l);
16+
l=l.next;
17+
}
18+
}
19+
20+
while(!q.isEmpty()){
21+
curr.next=q.poll();
22+
curr=curr.next;
23+
curr.next=null;
24+
}
25+
return ans.next;
26+
}
27+
}

0 commit comments

Comments
 (0)