题目描述
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
样例
输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
算法1
模拟
类似于多路归并算法以及上一次写的两个指针合并的问题,不过
在这里我们用的是小根堆可以每次从堆顶取得当前的最小值
C++ 代码
/**
* 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> heap;
auto dummy = new ListNode(-1), tail = dummy;
for(auto c:lists)if(c)heap.push(c);
while(heap.size()){
auto top = heap.top();
heap.pop();
tail = tail->next = top;
if(top->next)heap.push(top->next);
}
return dummy->next;
}
};