/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include<queue>
using namespace std;
//给优先级队列定义比较函数。让其从小到大
struct cmp {
bool operator()(const ListNode *a, const ListNode *b){
return a->val > b->val;
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
ListNode L(0);
ListNode *tail = &L;
priority_queue<ListNode *, vector<ListNode*>,cmp> Q;
//队列首部放入堆
for(auto &nd : lists){
if(nd == nullptr){
continue;
}
Q.push(nd);
}
while(!Q.empty()){
//堆顶弹出的是最小的
auto top = Q.top();
Q.pop();
if(top->next != nullptr){
//当前链表的下一个元素插入堆
Q.push(top->next);
}
//构造结果队列
tail->next = top;
top->next = nullptr;
tail = top;
}
return L.next;
}
};