- #include<iostream>
- using namespace std;
- template<typename T>class Quen{
- private:
- int front;
- int rear;
- T *base;
- int size;
- public:
- Quen(int k=1)
- {
- base=new T[k];
- front=rear=0;
- size=k;
- }
- ~Quen()
- {
- delete []base;
- }
- void clearQuen()
- {
- front=rear;
- }
- bool IsEmpty()
- {
- return rear==front;
- }
- int length()
- {
- return (rear-front+size)%size;
- }
- bool push(T e)
- {
- T *newbase;
- if((rear+1)%size==front)
- {
- newbase=new T[size*2];
- for(int i=0;i<size;i++)
- *(newbase+i)=*(base+(i+front)%size);
- delete []base;
- base=newbase;
- front=0;
- rear=front+size-1;
- size*=2;
- }
- *(base+rear)=e;
- rear=(rear+1)%size;
- return true;
- }
- bool pop(T &e)
- {
- if(rear==front)
- return false;
- e=*(base+front);
- front=(front+1)%size;
- }
- void visit()
- {
- for(int i=0;i<(rear-front+size)%size;i++)
- {
- cout<<*(base+(front+i)%size)<<",";
- }
- cout<<endl;
- }
- };
- int main()
- {
- Quen<int> Q;
- cout<<Q.length()<<endl;
- cout<<boolalpha<<Q.IsEmpty()<<endl;
- int i=1;
- while(i<5)
- {
- Q.push(i);
- cout<<Q.length()<<":";
- Q.visit();
- i++;
- }
- int e;
- Q.pop(e);
- cout<<Q.length()<<":";
- Q.visit();
- cout<<boolalpha<<Q.IsEmpty();
- }
- //该片段来自于http://www.codesnippet.cn/detail/300720134893.html
来源: http://www.codesnippet.cn/detail/300720134893.html