题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <queue> struct Compare { bool operator() (ListNode* p, ListNode* q) { return p->val > q->val; } }; class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类vector * @return ListNode类 */ priority_queue<int> res; ListNode* mergeKLists(vector<ListNode*>& lists) { // write code here priority_queue<ListNode*, vector<ListNode*>, Compare> pq; for (int i = 0; i < lists.size(); ++i) { if(lists[i]) pq.push(lists[i]); } ListNode node(-1),*p = &node; while (!pq.empty()) { ListNode * t = pq.top(); pq.pop(); p->next = t; p = t; if(t->next!=nullptr) { pq.push(t->next); } p->next = nullptr; } return node.next; } };