水完栈和队列之后,感觉常用的优先队列也不错,内部的排序是堆排序,感觉也不是很难,就直接写上了,但是实现的时候出现了一些问题,幸好有学长在旁边,帮助我解决了问题,在此感谢LYG学长;
对于排序,仍然自定义类型,然后对于优先级,进行重载,写完这个之后感觉对泛型的运用了解了一些,对堆的感觉也更强了点;
我是大顶堆排序,里面的元素重载了什么的一改就是自定义排序了
期间用到了析构函数,但是后来发现编译器会自动生成(如果没有的话),所以就删掉了
话不多说,直接上源码吧:
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<stdio.h>
#include<string.h>
#include<math.h>
//#include<map>
//#include<set>
#include<deque>
#include<queue>
#include<stack>
#include<bitset>
#include<string>
#include<fstream>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
//#define max(a,b) (a)>(b)?(a):(b)
//#define min(a,b) (a)<(b)?(a):(b)
#define clean(a,b) memset(a,b,sizeof(a))// 水印
//std::ios::sync_with_stdio(false);
const int MAXN=1e5+10;
const int INF=0x3f3f3f3f;
const ll mod=1e9+7;
struct Edge{
int data;
bool operator > (const Edge &a)const {
return a.data<data;
}
Edge(int _data=0):
data(_data){}
};
template<typename T>
class pQueue{
private://私有
//初始队列长度,初始队列最长度
int heapsize,max;
struct node{
T data;
}*pQ;
void SWAP(int a,int b);//交换队列中的两个节点
void heap_adjust(int rt);//维护大顶堆
public:
pQueue()
{
pQ=NULL;
heapsize=0;
max=0;
}
void push(T data);
T top();
void pop();
int size();
bool Empty();
};
template<typename T>
void pQueue<T>::SWAP(int a,int b)
{
node temp=pQ[a];
pQ[a]=pQ[b];
pQ[b]=temp;
}
template<typename T>
void pQueue<T>::heap_adjust(int rt)//维护大顶堆
{
int temp=rt;
int l=temp<<1,r=temp<<1|1;
if(l<=heapsize&&pQ[l].data>pQ[temp].data)
temp=l;
if(r<=heapsize&&pQ[r].data>pQ[temp].data)
temp=r;
//temp最大
if(temp!=rt)
{
SWAP(temp,rt);
heap_adjust(temp);
}
}
template<typename T>
void pQueue<T>::push(T data)
{
if(heapsize<max)//在范围内
{
pQ[++heapsize].data=data;
// pQ[heapsize].priority=0;
}
else
{
//与malloc的区别
pQ=(node*)realloc(pQ,(++heapsize+1)*sizeof(node));
//cout<<heapsize<<" "<<data.data<<" "<<max<<endl;
pQ[heapsize].data=data;
// pQ[heapsize].priority=0;
max++;
}
int index=heapsize;
int p=index>>1;
if(p==0)
return ;
while(p>=1&&pQ[index].data>pQ[p].data)
{
SWAP(index,p);
index=p;
p=index>>1;
}
heap_adjust(heapsize);
//提升优先级
}
template<typename T>
T pQueue<T>::top()
{
return pQ[1].data;
}
template<typename T>
void pQueue<T>::pop()
{
if(heapsize>1)
{
SWAP(1,heapsize);
heapsize--;
heap_adjust(1);
}
else
heapsize--;
}
template<typename T>
int pQueue<T>::size()
{
return heapsize;
}
template<typename T>
bool pQueue<T>::Empty()
{
return heapsize>1?1:0;
}
/*
1 6 3 4 9 12 50 32 16 53 465 321 20 3
*/
int main()
{
pQueue<Edge> que;
for(int i=1;i<15;++i)
{
int data;
cin>>data;
que.push(Edge(data));
cout<<"data:"<<que.top().data<<" size:"<<que.size()<<" isEmpty:"<<que.Empty()<<endl;
}
while(que.size())
{
cout<<que.top().data<<endl;
que.pop();
}
}
样例输出: