leetcode原题链接:合并K个升序链表
上一篇:HOT33-排序链表
下一篇:HOT35-LRU缓存
题目描述
给你一个链表数组,每个链表都已经按升序排列。请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入: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
示例 2:
输入:lists = [] 输出:[]
示例 3:
输入:lists = [[]] 输出:[]
提示:
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i]
按 升序 排列lists[i].length
的总和不超过10^4
解题方法:用小顶堆保存各个链表的最小值节点。开始时,将各个链表头节点push到堆中,使得堆的大小等于链表数组的个数。每次从堆顶弹出元素并压入结果链表中,并将堆顶元素对应链表的下一个节点压入栈中。这里C++语言实现有一个细节:std::greater表示小顶堆,std::less表示大顶堆,用lambda函数定义堆的cmp函数时要注意下。
C++代码
#include <iostream>
#include <queue> // std::priority_queue
#include <memory> // std::shared_ptr
#include <vector>
/**
* 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:
ListNode* mergeKLists(vector<ListNode*>& lists) {
int n = lists.size();
if (n <= 0) {
return nullptr;
}
if (n == 1) {
return lists[0];
}
auto cmp = [](ListNode* p1, ListNode* p2) {return p1 && p2 ? p1->val > p2->val : 0;}; //小顶堆,类std::greater
std::priority_queue<ListNode*, std::vector<ListNode*>, decltype(cmp)> prio_q(cmp);
//初始化优先级队列
for (int i = 0; i < n ; i++) {
ListNode* head = lists[i];
if (head) {
prio_q.push(head);
}
}
std::shared_ptr<ListNode> dummy_node(new ListNode(0));
ListNode* p_result = dummy_node.get();
if (!p_result) {
return nullptr;
}
while (!prio_q.empty()) {
// 弹出堆顶节点
ListNode* p_top = prio_q.top();
prio_q.pop();
// 更新结果链表
if (!p_result) {
return dummy_node->next;
}
p_result->next = p_top;
p_result = p_result ->next;
// 将堆顶节点的下一个非空节点压到堆中
if (p_top && p_top->next) {
prio_q.push(p_top->next);
}
}
return dummy_node->next;
}
};