Skip to content

Commit b693ca0

Browse files
authored
Create main.cpp
1 parent 780526a commit b693ca0

File tree

1 file changed

+48
-0
lines changed
  • 19 - Heap Data Structure Problems/13 - Merge K Sorted Lists

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
class Solution {
19+
public:
20+
ListNode* mergeKLists(vector<ListNode*>& lists) {
21+
priority_queue<ListNode*, vector<ListNode*>, compare> pq;
22+
23+
int k = lists.size();
24+
25+
if(k == 0) return NULL;
26+
for(int i = 0; i < k; i++) if(lists[i] != NULL) pq.push(lists[i]);
27+
28+
ListNode* head = NULL;
29+
ListNode* tail = NULL;
30+
31+
while(pq.size() > 0){
32+
ListNode* top = pq.top();
33+
pq.pop();
34+
35+
if(head == NULL){
36+
head = top;
37+
tail = top;
38+
}else{
39+
tail -> next = top;
40+
tail = top;
41+
}
42+
43+
if(top -> next != NULL) pq.push(top -> next);
44+
}
45+
46+
return head;
47+
}
48+
};

0 commit comments

Comments
 (0)