重写greater函数
重载函数使用结构体实现!!
struct cmp{ //对新的数据类型的 < 进行重写
bool operator()(ListNode *a,ListNode *b){
return a->val > b->val;
}
};
priority_queue<ListNode*, vector<ListNode*>, cmp> heap; // 小根堆
完整代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
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> q;
ListNode* head = new ListNode(0);
for(int i = 0;i < lists.size(); i ++ )
if(lists[i] != nullptr) q.push(lists[i]);
ListNode* work = head;
while(!q.empty())
{
work->next = q.top();
work = work->next;
q.pop();
if(work->next != nullptr) q.push(work->next);
}
return head->next;
}
};