合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
链接:🔗
1. 堆的形式存储k个链表的当前头结点
2. 设置为小根堆
3. 从堆中取出的链表结点ListNode,是可以继续使用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;
for (auto t:lists){
if (t) heap.push(t);
}
ListNode* dummy = new ListNode(0);
auto tail = dummy;
while(heap.size()){
auto t = heap.top(); // 取出头节点
heap.pop();
tail->next = t; // 插入排序的结果链表中
tail = t;
if (t->next) heap.push(t->next);
}
return dummy->next;
}
};