Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 602682b

Browse files
Add files via upload
1 parent daf2d9e commit 602682b

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

cpp/23-Merge-K-Sorted-Lists.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
12+
class compare{
13+
public:
14+
bool operator()(ListNode* a,ListNode* b){
15+
return a->val>b->val;
16+
}
17+
};
18+
19+
class Solution {
20+
public:
21+
ListNode* mergeKLists(vector<ListNode*>& lists) {
22+
23+
priority_queue<ListNode*,vector<ListNode*>,compare> pq;
24+
25+
for(int i=0;i<lists.size();i++){
26+
if(lists[i]!=NULL){
27+
pq.push(lists[i]);
28+
}
29+
}
30+
31+
if(pq.empty()){
32+
return NULL;
33+
}
34+
35+
ListNode* dummy=new ListNode;
36+
ListNode* last=dummy;
37+
38+
while(!pq.empty()){
39+
ListNode* curr=pq.top();
40+
pq.pop();
41+
42+
last->next=curr;
43+
last=last->next;
44+
45+
if(curr->next!=NULL){
46+
pq.push(curr->next);
47+
}
48+
}
49+
return dummy->next;
50+
}
51+
};

0 commit comments

Comments
 (0)