/**
* Definition for singly-linked list.
* 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) {}
* };
*/
struct heap{
int val,id;
heap(){}
heap(int _val,int _id):val(_val),id(_id){}
friend bool operator <(const heap b,const heap a){
return a.val<b.val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
const int N=lists.size();
if(!N) return nullptr;
ListNode* nxtNode[N];
priority_queue<heap> h;
for(int i=0;i<N;++i){
nxtNode[i]=lists[i];
if(nxtNode[i]==nullptr) continue;
h.push(heap(nxtNode[i]->val,i));
nxtNode[i]=nxtNode[i]->next;
}
heap top;
ListNode *head=nullptr,*lstNode=nullptr;
while(!h.empty()){
top=h.top();h.pop();
ListNode *now=new ListNode(top.val,nullptr);
if(lstNode==nullptr) head=now;
else lstNode->next=now;
lstNode=now;
if(nxtNode[top.id]!=nullptr){
h.push(heap(nxtNode[top.id]->val,top.id));
nxtNode[top.id]=nxtNode[top.id]->next;
}
}
return head;
}
};