题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
使用优先队列:
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; } };