#include<iostream>
#include<cstdlib>
using namespace std;
#define MAXSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int Status;
typedef int Elemtype;
typedef struct
{
Elemtype* base;//存储空间的基地址
int front;//头指针
int rear;//尾指针
}SqQueue;
Status InitQueue(SqQueue& Q);//初始化循环队列
Status CreatQueue(SqQueue& Q);//随即输入循环队列长度和队列整数型数据元素的值,创建一个队列
Status EnQueue(SqQueue& Q, int e);//将一个数插入到队尾(x在程序运行时随即输入)
Status DeQueue(SqQueue& Q);//删除循环队头元素,并在删除后输出队头元素
Status GetQueue(SqQueue Q);//判断循环队列是否为空,若不空输出队头元素
Status LenQueue(SqQueue Q);//获得循环队列的长度
Status PrintQueue(SqQueue Q);//输出循环队列中的所有元素
int main(void)
{
SqQueue Q;
int x;
int k;
do {
cout << "\n*****顺序循环队列相关操作*****";
cout << "\n1.初始化一个空的循环队列";
cout << "\n2.随机创建一个非空循环队列";
cout << "\n3.将一个数x插入到队尾";
cout << "\n4.将循环队列队头元素删除,并输出元素的值";
cout << "\n5.输出队头元素";
cout << "\n6.求顺序队列的长度";
cout << "\n7.输出顺序队列中所有的元素";
cout << "\n0.结束相关操作";
cout << "\n输入想要进行相关操作的序号:";
cin >> k;
switch (k)
{
case 1:
{
if (InitQueue(Q))
cout << "初始化成功。\n" << endl;
else
cout << "初始化失败。\n" << endl;
break;
}
case 2:
{
if (CreatQueue(Q))
{
cout << "创建成功。\n";
}
else
{
cout << "创建失败。\n";
}
break;
}
case 3:
{
cout << "输入想要插入元素的数值x为:";
cin >> x;
if (EnQueue(Q, x)) cout << "插入成功。\n";
else cout << "插入失败。\n";
break;
}
case 4:
{
if (DeQueue(Q)) cout << "删除成功。\n";
else cout << "删除失败。\n";
break;
}
case 5:
{
if (GetQueue(Q)) cout << "输出成功。\n";
else cout << "输出失败。\n";
break;
}
case 6:
{
if (LenQueue(Q)) cout << "长度获取成功。\n";
else cout << "长度获取失败。\n";
break;
}
case 7:
{
if (PrintQueue(Q)) cout << "全部输出成功。\n";
else cout << "全部输出失败。\n";
break;
}
}
} while (k != 0);
return OK;
}
Status InitQueue(SqQueue& Q)//初始化循环队列
{
Q.base = new Elemtype[MAXSIZE];//为队列分配一个最大容量为MAXSIZE的数组空间
if (!Q.base) exit(OVERFLOW);
Q.front = Q.rear = 0;
return OK;
}
Status CreatQueue(SqQueue& Q)//随即输入循环队列长度和队列整数型数据元素的值,创建一个队列
{
int len = 0;
cout << "\n输入循环队列的长度len:";
cin >> len;
cout << "\n输入循环队列整数型数据元素的数据:";
for (int i = 0; i < len; i++)
{
cin >> Q.base[Q.rear];//进队尾
Q.rear = (Q.rear + 1) % MAXSIZE;//队尾加一
}
return OK;
}
Status EnQueue(SqQueue& Q, int e)//将一个数插入到队尾(x在程序运行时随即输入)
{
if ((Q.rear + 1) % MAXSIZE == Q.front) return ERROR;//循环队列满
Q.base[Q.rear] = e;//进队尾
Q.rear = (Q.rear + 1) % MAXSIZE;//队尾加一
return OK;
}
Status DeQueue(SqQueue& Q)//删除循环队头元素,并在删除后输出队头元素
{
if (Q.front == Q.rear) return ERROR;
int e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXSIZE;//队头指针加一
cout << "删除的循环队列的元素为:" << e << endl;
return OK;
}
Status GetQueue(SqQueue Q)//判断循环队列是否为空,若不空输出队头元素
{
if (Q.front == Q.rear) return ERROR;
cout << "循环队列的队头元素为:" << Q.base[Q.front] << endl;
return OK;
}
Status LenQueue(SqQueue Q)//获得循环队列的长度
{
cout << "循环队列的长度为:" << (Q.rear - Q.front + MAXSIZE) << endl;
return OK;
}
Status PrintQueue(SqQueue Q)//输出循环队列中的所有元素
{
cout << "\n循环队列的元素为:";
for (int i = Q.front; i != Q.rear; i++)
{
cout << Q.base[i] << " ";
}
return OK;
}