学习了优先权队列的使用方法,引入头文件,写一个比较函数,可以当作最小堆、最大堆使用
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
struct Status {
int value;
ListNode* ptr;
bool operator < (const Status& that) const {
return value > that.value; //最大堆,反之最小堆
}
};
priority_queue <Status> q;
ListNode* mergeKLists(vector<ListNode*>& lists) {
for (auto node : lists) {
if (node) q.push({ node->val, node }); // 在优先权队列中依次插入各个list首节点
}
ListNode head, * tail = &head;
while (!q.empty()) {
auto f = q.top(); q.pop(); //f是优先级队列中弹出的最大status
tail->next = f.ptr;
tail = tail->next; //最大的放最后面
if (f.ptr->next) q.push({ f.ptr->next->val, f.ptr->next });
}
return head.next;
}
};
int main() {
Solution test;
ListNode* a = new ListNode(1);
a->next= new ListNode(4);
a->next->next = new ListNode(5);
ListNode* b = new ListNode(1);
b->next = new ListNode(3);
b->next->next = new ListNode(4);
ListNode* c = new ListNode(2);
c->next = new ListNode(6);
vector<ListNode*>lists(3);
lists.push_back(a);
lists.push_back(b);
lists.push_back(c);
ListNode* ans = test.mergeKLists(lists);
while (ans) {
cout << ans->val<<" ";
ans = ans->next;
}
return 0;
}