使用优先队列:
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if(lists.empty()) return nullptr;
struct cmp_custom {//比较器
bool operator()(ListNode* &x, ListNode* &y) {
return (x->val) > (y->val);//递减
}
};
priority_queue<ListNode*,vector<ListNode*>,cmp_custom> p;
for(int i=0;i<lists.size();++i){
if(lists[i])
p.push(lists[i]);
}
ListNode* head=p.top();
ListNode* res=head;
p.pop();
while(!p.empty()){
if(head->next)
p.push(head->next);
head->next=p.top();
p.pop();
head=head->next;
}
return res;
}
};



京公网安备 11010502036488号