Skip to content

Commit 9b3d283

Browse files
committed
leetcode 23
1 parent c6d8d1f commit 9b3d283

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

23. Merge k Sorted Lists.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
class Solution {
12+
public:
13+
ListNode* mergeKLists(vector<ListNode*>& lists) {
14+
ListNode* res = new ListNode(0);
15+
ListNode* temp = res;
16+
17+
priority_queue<int, vector<int>, greater<int>> minHeap;
18+
19+
for (auto l : lists) {
20+
while (l != nullptr) {
21+
minHeap.push(l->val);
22+
l = l->next;
23+
}
24+
}
25+
26+
while (!minHeap.empty()) {
27+
int num = minHeap.top();
28+
minHeap.pop();
29+
30+
temp->next = new ListNode(num);
31+
temp = temp->next;
32+
}
33+
34+
return res->next;
35+
}
36+
};

0 commit comments

Comments
 (0)