循环队列
注意:
代码如下:
#include <iostream>
#include <stdlib.h>
#define MAXQSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int QElemType_CSq;
typedef int Status;
using namespace std;
//定以队列的顺序存储结构
typedef struct
{
QElemType_CSq *base;//用于动态分配空间
int front;//队头索引
int rear;//队尾索引
}CSqQueue;
//初始化
Status InitQueue_CSq(CSqQueue &Q)
{
Q.base = (QElemType_CSq *)malloc(MAXQSIZE*sizeof(QElemType_CSq));
if (!Q.base)
exit(OVERFLOW);
Q.front = Q.rear = 0;
return OK;
}
//入队
Status EnQueue_CSq(CSqQueue &Q)
{
int n,e;
cout<<"请输入要入队的元素个数:"<<endl;
cin>>n;
cout<<"请依次输入要入队的元素:"<<endl;
for (int i=0;i<n;i++)
{
cin>>e;
if ((Q.rear + 1)%MAXQSIZE == Q.front)
{
cout<<"循环队列已满"<<endl;
return ERROR;
}
Q.base[Q.rear] = e;
Q.rear = (Q.rear+1)%MAXQSIZE;
}
cout<<"入队成功"<<endl;
return OK;
}
//显示循环队列
void QueueTraverse_CSq(CSqQueue Q)
{
int i = Q.front;
cout<<"循环队列内元素为:"<<endl;
while (i!=Q.rear)
{
cout<<Q.base[i]<<" ";
i = (i+1)%MAXQSIZE;
}
cout<<endl;
}
//清空循环队列
void ClearQueue_CSq(CSqQueue &Q)
{
Q.front = Q.rear = 0;
cout<<"清空成功"<<endl;
}
//判断队列是否为空
void QueueEmpty_CSq(CSqQueue Q)
{
if (Q.front == Q.rear)
cout<<"队列为空"<<endl;
else
cout<<"队列不为空"<<endl;
}
//求循环队列长度
int QueueLength_CSq(CSqQueue Q)
{
return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}
//取队头元素
Status GetHead_CSq(CSqQueue Q)
{
int e;
if (Q.front == Q.rear)
{
cout<<"队列为空,无队头元素"<<endl;
return ERROR;
}
e = Q.base[Q.front];
cout<<"队头元素为:"<<e<<endl;
return OK;
}
//出队
Status DeQueue_CSq(CSqQueue &Q)
{
if (Q.front == Q.rear)
{
cout<<"队列为空,无法出队"<<endl;
return ERROR;
}
int e;
e = Q.base[Q.front];
Q.front = (Q.front+1)%MAXQSIZE;
cout<<"队头元素"<<e<<"出队成功"<<endl;
return OK;
}
void show_help()
{
cout<<"******* Data Structure ******"<<endl;
cout<<"1----清空循环队列"<<endl;
cout<<"2----判断循环队列是否为空"<<endl;
cout<<"3----求循环队列长度"<<endl;
cout<<"4----获取队头元素"<<endl;
cout<<"5----入队"<<endl;
cout<<"6----出队"<<endl;
cout<<"7----显式循环队列"<<endl;
cout<<" 退出,输入0"<<endl;
}
int main()
{
int operate_code;
show_help();
CSqQueue Q;
InitQueue_CSq(Q);
while(1)
{
cout<<"";
cin>>operate_code;
if(operate_code==1)
{
ClearQueue_CSq(Q);
}
else if (operate_code==2)
{
QueueEmpty_CSq(Q);
}
else if (operate_code==3)
{
cout<<"循环队列的长度为:"<<QueueLength_CSq(Q)<<endl;
}
else if (operate_code==4)
{
GetHead_CSq(Q);
}
else if (operate_code==5)
{
EnQueue_CSq(Q);
}
else if (operate_code==6)
{
DeQueue_CSq(Q);
}
else if (operate_code==7)
{
QueueTraverse_CSq(Q);
}
else if (operate_code==0)
{
break;
}
else
{
cout<<"\n操作码错误!!!"<<endl;
show_help();
}
}
//调用销毁线性表函数,如Destroy_List(L);
return 0;
}