
一、题目描述

二、算法原理
思路:最小堆

1)首先弄出这样的堆,这个堆里面的结点保存的是每个链表的地址
2)每次拿出堆顶的结点,这个结点就是这么多个链表里面里面的最小值的结点
3)把堆顶的元素出堆
4)如果这个拿出堆顶的结点还有下一个结点,也就是说这个结点的下一个结点不为 nullptr ,则再把这个结点的下一个结点入堆。
5)重复上面的操作,直到这个堆为空
三、代码实现
cpp
/**
* 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) {}
* };
*/
struct CampareNode//自定义最小堆的比较函数
{
bool operator()(ListNode* x,ListNode* y)
{
return x->val > y->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
//初始化最小堆
priority_queue<ListNode*,vector<ListNode*>,CampareNode> minheap;
//把所有链表入堆
for(auto& e : lists) if(e) minheap.push(e);
//自定义一个链表
ListNode* head = new ListNode(0);//哨兵结点
ListNode* cur = head;
while(minheap.size())
{
ListNode* tmp = minheap.top();//获取堆顶元素
minheap.pop();//出堆
cur->next = tmp;
cur = tmp;
if(tmp->next) minheap.push(tmp->next);
}
cur->next = nullptr;
ListNode* result = head->next;
delete head;//释放哨兵结点
return result;
}
};