本文采用“队列头指针在队列尾指针的下一个位置上表示队列满”(即少用一个元素空间)的方式来书写代码
本文的思路主要参考严蔚敏老师编写的《数据结构》
//循环队列
#include <iostream>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define MAXQSIZE 100
#define QElemType int
typedef int Status;
using namespace std;
typedef struct
{
QElemType *base; //初始化的动态分配存储空间
int thefront;
int therear;
}SqQueue;
Status InitQueue(SqQueue &Q)
{//初始化一个空的循环队列
Q.base=(QElemType*)malloc(MAXQSIZE*sizeof(QElemType));
if(!Q.base)
exit(OVERFLOW);
else
{
Q.thefront=Q.therear=0;
return OK;
}
}
int QueueLength(SqQueue Q)
{
return(Q.therear-Q.thefront+MAXQSIZE)%MAXQSIZE;
}
//Status EnQueue(SqQueue &Q,QElemType e)
//{//插入新的元素e为Q的新的队尾元素
// if(Q.thefront==Q.therear=0)
// Q.thefront=e;
// else
// {
// Q.therear=e;
// Q.therear+=1;
// }
//}
Status EnQueue(SqQueue &Q,QElemType e)
{//插入新的元素e为Q的新的队尾元素
if((Q.therear+1)%MAXQSIZE==Q.thefront)//若队列满
return ERROR;
Q.base[Q.therear]=e;
Q.therear=(Q.therear+1)%MAXQSIZE;//将队尾的值加一
return OK;
}
Status DeQueue(SqQueue &Q,QElemType &e)
{//若队列不空,则删除Q的队头元素,用e返回其值,并返回OK,否则返回error
if(Q.thefront==Q.therear)
return ERROR;
e=Q.base[Q.thefront];
Q.thefront=(Q.thefront+1)%MAXQSIZE;
return OK;
}
void PrintQueue(SqQueue q)
{//若循环队列不为空,则输出循环队列中的元素,否则输出null
if(q.thefront==q.therear)
cout<<"null"<<endl;
else if(q.thefront<q.therear)
{
int i;
for(i=q.thefront;i<q.therear;i++)
{
cout<<q.base[i]<<" ";
}
cout<<endl;
}
else if(q.thefront>q.therear)
{
int i;
for(i=q.thefront;i<MAXQSIZE;i++)
{
cout<<q.base[i]<<" ";
}
for(i=0;i<q.therear;i++)
{
cout<<q.base[i]<<" ";
}
cout<<endl;
}
}
int main()
{
SqQueue a;
InitQueue(a);
EnQueue(a,1);
EnQueue(a,2);
EnQueue(a,3);
PrintQueue(a);
QElemType b;
DeQueue(a,b);
PrintQueue(a);
}
运行结果:
若以上代码有任何错误或需要改进的地方欢迎在评论区指出并讨论