题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类vector * @return ListNode类 */ struct cmp{ bool operator()(ListNode* l1,ListNode* l2){ return l1->val>l2->val; } }; ListNode* mergeKLists(vector<ListNode*>& lists) { // write code here priority_queue<ListNode*,vector<ListNode*>,cmp> pq; for(auto list:lists) if(list) pq.emplace(list); auto dummy=new ListNode(0); ListNode* cur=dummy; while(!pq.empty()){ auto list=pq.top(); pq.pop(); cur->next=list; cur=cur->next; list=list->next; if(list) pq.emplace(list); } return dummy->next; } };