我这里就不展示题目啦 => 自己到力扣上看一眼就行
经过大牛指点 => 得到一种新的最小堆写法:构造函数传参
auto cmp = [](ListNode *lh, ListNode *rh) { return lh->val > rh->val; };
std::priority_queue<ListNode *, std::vector<ListNode *>, decltype(cmp)> pq(cmp);
我这里是用来练习刚学习到的优先级队列(最小堆)来解决问题:
class Solution {
public:
struct cmp {
bool operator()(ListNode* a, ListNode* b) {
return a->val > b->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
// 不要被题目误导啦!形参lists里面存放的是每条链表的第一个结点
// 只是样例看上去容易误会成 => vector<vector<ListNode*>>
ListNode* dummy = new ListNode(-1);
ListNode* p = dummy;
priority_queue<ListNode*, vector<ListNode*>, cmp> pq;
for(auto head: lists) {
if(head) pq.push(head);
}
while(!pq.empty()) {
// 将k个链表的头节点加入最小堆
auto node = pq.top();
pq.pop();
p->next = node;
// 相当于把链表打散勒 => 不断香气中加入结点根据val形成最小堆
if(node->next) pq.push(node->next);
p = p->next;
}
return dummy->next;
}
};
需要注意的一个细节就是:别被题目的样例误导,我刚开始一直认为形参是vector<vector<ListNode*>> lists (有时候眼睛干不过脑子) 其实并不是,lists里面存放的是每条链表的头指针!
我这里提供一下全代码 => 方便那些找不到问题所在的小伙伴调试
#include <bits/stdc++.h>
using namespace std;
typedef struct ListNode {
int val;
struct ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
} Node, *List;
Node* add(List head, int num) {
Node* p = new ListNode(num);
head->next = p;
return p;
}
void create(List dummy) {
int num;
Node* head = dummy;
vector<List> list;
while(1){
cin >> num;
if(num == -1) break;
head = add(head, num);
list.push_back(head);
}
}
struct cmp {
bool operator()(ListNode* a, ListNode* b) {
return a->val > b->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* dummy = new ListNode(-1);
ListNode* p = dummy;
priority_queue<ListNode*, vector<ListNode*>, cmp > pq;
for(auto head: lists) {
if(head) pq.push(head);
}
while(!pq.empty()) {
// 将k个链表的头节点加入最小堆
auto node = pq.top();
pq.pop();
p->next = node;
if(node->next) pq.push(node->next);
p = p->next;
}
return dummy->next;
}
void print(List head) {
if(head == NULL) {
cout << "NULL";
return;
}
List p = head;
while(p->next) {
cout << p->val << " ";
p = p->next;
}
cout << p->val;
}
int main() {
vector<ListNode*> lists;
int n;
cin >> n;
while(n--) {
Node* dummy = new ListNode(-1);
dummy->next = NULL;
create(dummy);
lists.push_back(dummy->next);
}
print(mergeKLists(lists));
return 0;
}