**
STL里的priority_queue用法总结
**
priority_queue<Type, Container, Functional>
Type为数据类型, Container为保存数据的容器,Functional为元素比较方式。
如果不写后两个参数,那么容器默认用的是vector,比较方式默认用operator<,也就是优先队列是大顶堆,队头元素最大。当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆
升序队列:
priority_queue <int,vector,greater > q;
降序队列:
priority_queue <int,vector,less >q;
代码说明:
以下是priority_queue的自定义数据将链表数组合并到一个升序链表中,返回合并后的链表,而且比较函数compare里面的如果改成< 也就是降序的话,以下代码不适用降序链表数组需要修改代码!
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct compare {
bool operator()(const ListNode* a, const ListNode* b) const
{ return a->val > b->val; }
};
void printList(ListNode* head)
{
ListNode* phead=head;
while(phead!=NULL)
{
cout<<phead->val<<" ";
phead=phead->next;
}
cout<<"\n";
}
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
// 解法1:优先队列,小根堆,priority_queue默认是大根堆
priority_queue<ListNode*, vector<ListNode*>, compare> pq;
for (size_t i = 0; i < lists.size(); ++i) {
if (lists[i]) {
pq.push(lists[i]);
}
}
ListNode dummy_head(-1);
ListNode* pre = &dummy_head;
while (!pq.empty()) {
ListNode* topNode = pq.top();
pq.pop();
pre->next = topNode;
pre = pre->next;
if (topNode->next) {
pq.push(topNode->next); // 如果取出的这个下一个不为bullptr,则继续加入队列哈
}
}
return dummy_head.next;
}
};
int main()
{
Solution s;
ListNode* p1 = new ListNode(2);
ListNode* p2 = new ListNode(5);
ListNode* p3 = new ListNode(4);
ListNode* p4 = new ListNode(1);
ListNode* p5 = new ListNode(3);
ListNode* p6 = new ListNode(6);
p1->next = p2;
p2->next = p3;
p4->next = p5;
p5->next = p6;
printList(p1);
printList(p4);
vector<ListNode*> list;
list.push_back(p1);
list.push_back(p4);
ListNode* p7 = s.mergeKLists(list);
printList(p7);
return 0;
}