c++队列
#include<iostream> using std::cin; using std::cout; using std::endl; typedef int type; namespace myqueue { class queue { enum{q_size=100}; struct Node{ type data; Node*next; }; Node *front; Node *rear; const int Maxsize; int items; public: queue(int z=q_size):Maxsize(z){ front=rear=NULL; items=0; } ~queue(); bool isempty();//判断队空 bool isfull();//判断队满 int queuecount();//返回队列当前元素数量 bool enqueue(const type&x);//入队 bool dequeue(type &x);//出队并通过引用x返回队首 bool dequeue();//重载出队,仅返回是否出队成功 void show();//显示整个队列 void fill();//填满整个队列用于测试 }; queue::~queue(){ Node*p; while(front){ p=front; front=front->next; delete p; } } bool queue::isempty(){ return items==0; } bool queue::isfull(){ return items==Maxsize; } int queue:: queuecount(){ return items; } bool queue::enqueue(const type&x){ if(items==Maxsize) return false; Node *p=new Node; p->data=x; p->next=NULL; items++; if(front==NULL) front=p; else rear->next=p; rear=p; return true; } bool queue::dequeue(type &x){ if(front==NULL) return false; x=front->data; Node*temp=front; items--; front=front->next; delete temp; if(items==0) rear=NULL; return true; } bool queue::dequeue(){ if(front==NULL) return false; Node*temp=front; items--; front=front->next; delete temp; if(items==0) rear=NULL; return true; } void queue::show(){ cout<<"Maxsize:"<<Maxsize<<endl<<"items:"<<items<<endl; Node *p=front; while(p){ cout<<p->data<<" "; p=p->next; } cout<<endl; } void queue:: fill(){ for(int i=0;i<Maxsize;i++) this->enqueue(i); } } int main() { using namespace myqueue; queue one; one.fill(); one.show(); cout<<one.queuecount(); }
版权声明:本文为博主原创文章,未经博主允许不得转载。