Skip to content

Commit 7e0d648

Browse files
committed
Merge K Sorted Lists Solution
1 parent 5f9eca0 commit 7e0d648

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

merge-k-sorted-lists/PDKhan.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)