We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 5f9eca0 commit 7e0d648Copy full SHA for 7e0d648
merge-k-sorted-lists/PDKhan.cpp
@@ -0,0 +1,36 @@
1
+struct Compare{
2
+ bool operator()(ListNode* a, ListNode* b){
3
+ return a->val > b->val;
4
+ }
5
+};
6
+
7
+class Solution {
8
+public:
9
+ ListNode* mergeKLists(vector<ListNode*>& lists) {
10
+ priority_queue<ListNode*, vector<ListNode*>, Compare> pq;
11
+ ListNode* head = nullptr;
12
+ ListNode* tail;
13
14
+ for(ListNode* node : lists){
15
+ if(node) pq.push(node);
16
17
18
+ while(!pq.empty()){
19
+ ListNode* node = pq.top();
20
21
+ pq.pop();
22
+ if(head == nullptr){
23
+ head = node;
24
+ tail = head;
25
+ }else{
26
+ tail->next = node;
27
+ tail = tail->next;
28
29
30
+ if(node->next)
31
+ pq.push(node->next);
32
33
34
+ return head;
35
36
0 commit comments