#include<assert.h>
#include<iostream.h>
#include<stdlib.h>
using namespace std;
const int DefaultSize=50;
template<class T>
class PQueue{
protected:
T *PQelem;
int count;
int maxSize;
void adjust();
public:
PQueue(int size=DefaultSize);
~PQueue(){delete []PQelem;}
bool Insert(const T &x);
bool RemoveMin(T &x);
bool getFront(T &x)const;
void makeEmpty(){count=0;}
bool IsEmpty()const{return (count==0)?true:false;}
bool IsFull()const{return (count==maxSize)?true:false;}
int getSize()const{return count;}
};
template<class T>
PQueue<T>::PQueue(int size):count(0),maxSize(size){
PQelem=new T[size];
assert(PQelem!=NULL);
}
template<class T>
bool PQueue<T>::Insert(const T &x){
if(IsFull())
return false;
//the final position
PQelem[count]=x;
count++;
adjust();
return true;
}
template<class T>
void PQueue<T>::adjust(){
//min elem should be set at [0]
T temp=PQelem[count-1];
int i;
for(i=count-2;i>=0;i--){
if(PQelem[i]<=temp)
//go insert
break;
else
//go move elem
PQelem[i+1]=PQelem[i];
}
PQelem[i+1]=temp;
}
template<class T>
bool PQueue<T>::RemoveMin(T &x){
if(IsEmpty())
return false;
x=PQelem[0];
for(int i=1;i<getSize();i++){
PQelem[i-1]=PQelem[i];
}
count--;
return true;
}
template<class T>
bool PQueue<T>::getFront(T &x)const{
if(IsEmpty())
return false;
x=PQelem[0];
return true;
}
栈和队列的物理实现(优先级)
class PQStack{
protected:
PQueue<T> pq;
public:
PQStack(int sz=50){pq=new PQStack<T>(sz);assert(PQueue!=NULL);}
~PQStack(){pq.makeEmpty();}
bool IsEmpty()const{return pq.IsEmpty();}
bool IsFull()const{return pq.IsFull();}
bool Push(const T &x){return pq.Insert(x);}
bool Pop(T &x){
x=pq.PQelem[count-1];
pq.count--;
}
bool Top(T &x){return pq.PQelem[pq.count-1];}
int Size()const{return pq.getSize();}
};
class PQQueue{
protected:
PQueue<T> pq;
public:
PQQelem(int sz=10):{
pq=new PQueue<T>(sz);
assert(PQueue!=NULL);
}
~PQQelem(){pq.makeEmpty();}
bool IsEmpty()const{return pq.IsEmpty();}
bool IsFull()const{return pq.IsFull();}
bool EnQueue(const T &x){
return pq.Insert(x);
}
bool DeQueue(T &x){
return pq.RemoveMin(x);
}
int getSize()const{
return pq.count;
}
bool getFront(T &x)const{
return pq.getFront()
}
};