题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
struct LISTNODECOMPARE {
bool operator()(ListNode* a, ListNode* b) {
return a->val >= b->val;
}
};
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类vector
* @return ListNode类
*/
ListNode *mergeKLists(vector<ListNode *> &lists)
{
priority_queue<ListNode *, vector<ListNode *>, LISTNODECOMPARE> pq;
for (auto &l : lists)
{
if (l != nullptr)
pq.push(l);
}
ListNode *head = nullptr;
ListNode *tail = nullptr;
while (!pq.empty())
{
auto a = pq.top();
ListNode *b = a->next;
a->next = nullptr;
pq.pop();
if (!head)
{
head = a;
tail = head;
}
else
{
tail->next = a;
tail = tail->next;
}
if (b)
pq.push(b);
}
return head;
}
};
对每个头节点进行堆排序
