/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <queue>
struct Compare {
bool operator() (ListNode* a, ListNode* b) {
return a->val > b->val;
}
};
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类vector
* @return ListNode类
*/
ListNode* mergeKLists(vector<ListNode*>& lists) {
// write code here
// 用最小堆,找到最小的节点,加入结果链表中,C++ 里是优先队列实现的
priority_queue<ListNode*, vector<ListNode*>, Compare> pq;
// 将每个链表的头节点加入最小堆
for (ListNode* list : lists) {
if (list) {
pq.push(list);
}
}
ListNode dummy(0);
ListNode* tail = &dummy;
while (!pq.empty()) {
ListNode* minNode = pq.top();
pq.pop();
tail->next = minNode;
tail = tail->next;
if (minNode->next) {
pq.push(minNode->next);
}
}
return dummy.next;
}
};