题目
解法
/**
* 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) {
if(lists.empty()) return NULL;
// 使用优先级队列,每次弹出最小值
priority_queue<ListNode* ,vector<ListNode*> , cmp> heapk;
for(auto list : lists){
if(list) heapk.push(list);
}
ListNode *res = new ListNode(-1);
ListNode *tempRes = res;
while(!heapk.empty()){
ListNode *top = heapk.top();
heapk.pop();
tempRes->next = top;
tempRes = tempRes->next;
if(top->next) heapk.push(top->next);
}
tempRes = res->next;
delete res;
return tempRes;
}
};