循环队列实现及基本操作
#include<iostream>
#define MAXQUEUESIZE 100
using namespace std;
typedef struct CircularQueue//循环队列结构
{
int *base;
int front;
int rear;
}CQ;
CQ CreateCircularQueue()//创建空队列
{
CQ Q;
Q.base=new int[MAXQUEUESIZE];
if(!Q.base)
cout<<“内存分配失败!”<<endl;
Q.front=Q.rear=0;
return Q;
}
CQ InitQueue(CQ Q)
{
int num,i;
cout<<“输入要初始化元素个数:”;
cin>>num;
for(i=0;i<num;i++)
{
cout<<“输入元素:”;
cin>>Q.base[Q.rear];
Q.rear=(Q.rear+1)%MAXQUEUESIZE;
}
return Q;
}
CQ EnterQueue(CQ Q,int n)//插入n为新的队尾元素
{
if(((Q.rear+1)%MAXQUEUESIZE)==Q.front)
{
cout<<“队列已满,无法入队列”<<endl;
}
else
{
Q.base[Q.rear]=n;
Q.rear=(Q.rear+1)%MAXQUEUESIZE;
}
return Q;
}
CQ OutQueue(CQ Q)//队头元素出队列
{
if(Q.front==Q.rear)
cout<<“队列为空”<<endl;
else
Q.front=(Q.front+1)%MAXQUEUESIZE;
return Q;
}
int QueueLength(CQ Q)
{
return (Q.rear-Q.front+MAXQUEUESIZE)%MAXQUEUESIZE;//注意要加上MAXQUEUESIZE,否则可能出现长度为负数
}
void PrintQueue(CQ Q)
{
int i;
i=Q.front;
while(((i+1)%MAXQUEUESIZE)!=Q.rear)
{
cout<<Q.base[i]<<“–>”;
i=(i+1)%MAXQUEUESIZE;
}
cout<<Q.base[i]<<endl;
}
CQ EmptyQueue(CQ Q)
{
Q.front=Q.rear=0;
return Q;
}
void DestroyQueue(CQ Q)
{
delete[] Q.base;
}
int main()
{
CQ Q;
int choice,n;
Q=CreateCircularQueue();
Q=InitQueue(Q);
while(1)
{
system(“pause”);
system(“cls”);
cout<<“1.元素入队列”<<endl;
cout<<“2.队头元素出队列”<<endl;
cout<<“3.打印队列元素”<<endl;
cout<<“4.队列长度”<<endl;
cout<<“5.清空队列”<<endl;
cout<<“0.退出程序”<<endl;
cout<<“选择操作:”;
cin>>choice;
switch(choice)
{
case 1:cout<<“输入入队元素:”;cin>>n;Q=EnterQueue(Q,n);break;
case 2:Q=OutQueue(Q);break;
case 3:cout<<“循环队列为:”;PrintQueue(Q);break;
case 4:cout<<“队列长度为:”<<QueueLength(Q)<<endl;break;
case 5:Q=EmptyQueue(Q);break;
case 0:DestroyQueue(Q);exit(0);
}
}
return 0;
}