#include
using namespace std;
enum Result{Overflow,Underflow};
template
class PrioQueue
{
public:
PrioQueue()
{
maxSize=20;
n=0;
q=new T[maxSize];
}
PrioQueue(T* head,int length)
{
maxSize=length+1;
n=length;
q=new T[length];
for(int i=0;i q[i]=head[i];
CreateHeap(length);
}
~PrioQueue(){delete q;}
void Append(const T& x);
void Serve(T& x);
bool IsEmpty() const
{
return n==0;
}
bool IsFull() const
{
return n==20;
}
private:
T* q;
void AdjustDown(int r,int j);
void AdjustUp(int j);
void CreateHeap(int n);
// void Print();
int n,maxSize;
};
template
void PrioQueue::AdjustDown(int r,int j)
{
T temp=q[r];
int m=2*r+1;
while(m<=j)
{
if((q[m]>q[m+1])&&(mm=m+1;
if(temp>q[m])
q[(m-1)/2]=q[m];
m=2*m+1;
}
q[(m-1)/2]=temp;
}
template
void PrioQueue::AdjustUp(int j)
{
T temp=q[j];
int m=j;
while((m>0)&&(q[(m-1)/2]>temp))
{
q[m]=q[(m-1)/2];
m=(m-1)/2;
}
q[m]=temp;
}
template
void PrioQueue::Serve(T& x)
{
if(IsEmpty()) throw Overflow;
x=q[0];
q[0]=q[n-1];
AdjustDown(0,n-1);
n=n-1;
}
template
void PrioQueue::Append(const T& x)
{
if(IsFull()) throw Underflow;
q[n++]=x;
AdjustUp(n-1);
//Print();
}
template
void PrioQueue::CreateHeap(int n)
{
for(int i=(n-1)/2;i>-1;i--)
AdjustDown(i,n-1);
}
/*
template
void PrioQueue::Print()
{
for(int i=0;i cout<>endl;
}
*/
int main()
{
int x[6]={62,18,30,46,50,70};
int e;
PrioQueue m=PrioQueue(x,6);
try
{
m.Serve(e);
cout<system("pause");
}
catch(Result err)
{
switch(err)
{
case Underflow:
cout<<"underflow"<break;
case Overflow:
cout<<"overflow"<break;
}
}
}
阅读(2390) | 评论(0) | 转发(0) |