和链表一样,就多一个堆而已
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
struct cmp
{
bool operator()(ListNode* a, ListNode* b)
{
return a->val>b->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, cmp>a;
if(lists.empty())
return nullptr;
for(auto listVec : lists)
if(nullptr!=listVec)
a.push(listVec);
ListNode head = ListNode(-1);
auto node = &head;
while(!a.empty())
{
node->next = a.top();
if(a.top()->next != nullptr)
a.push(a.top()->next);
a.pop();
node = node->next;
}
return head.next;
}
};