一、算法
构造函数:初始化一个空的循环队列,将队头指针和队尾指针同时指向数组的高端,即rear=front=size-1;
析构函数:为空;
入队:当队满时,抛出“上溢”;队尾指针在循环意义下加一,在队尾处插入元素x;
出队:当队空时,抛出“下溢”;队头指针在循环意义下加一,读取并返回队头元素;
读取队头元素:当队空时,抛出“下溢”;设置i赋值为队头指针加一对长度的取余;返回i;
判空:如果rear==front,则队为空,返回1,否则,返回0;
输出:当rear==front时,输出“该队列为空”,定义一个i,当 i!=rear+1 时,输出 i;
二、源代码
#include
using namespace std;
const int size=100;
template
class cirqueue
{
public:
cirqueue(){front=rear=size-1;}
~cirqueue(){}
void enqueue(T x);
T dequeue();
T getqueue();
int empty(){if(front==rear)return 1;else return 0;}
void print();
private:
T data[size];
int front,rear;
};
template
void cirqueue::enqueue(T x)
{
if((rear+1)%size==front)
throw"error";
rear=(rear+1)%size;
data[rear]=x;
}
template
T cirqueue::dequeue()
{
if(rear==front)
throw"error";
front=(front+1)%size;
return data[front];
}
template
T cirqueue::getqueue()
{
int i;
if(rear==front)
throw"error";
i=(front+1)%size;
return data[i];
}
template
void cirqueue::print()
{
int i;
if(rear==front)
cout<<"the cirqueue is empty!"<cir;
while(flag==1)
{
cout<<"please input the command:"<>t;
switch(t)
{
case 1:
{
cout<<"please enter the element to be pushed in:";
while(x)
{
cin>>x;
if(x!=0)
cir.enqueue(x);
}
cout<
三、运行结果
输入1,将23 45 56 67 89 90 依次入队,当输入0时,停止入队。
输入2,将队头元素23出队;
输入3,输出此时队头元素45;
输入4,判断队列是否为空,为空,输出1,否则输出0,此队列非空,输出0;
输入5,输出此队列所有元素;
输入6,退出。
