实现循环队列的基本操作:
#include
#include
#include
using namespace std;
#define MAXQSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define False 0
#define True 1
typedef int Status;
typedef int QElemType;
typedef struct
{
QElemType *base; //存储空间的基地址
int front; //头指针
int rear; //尾指针
}SqQueue;
//循环队列的初始化
Status InitQueue(SqQueue &q)
{
q.base = new QElemType[MAXQSIZE]; //为队列分配一个最大容量为 MAXQSIZE 的数组空间
if(!q.base) exit(OVERFLOW); //存储分配失败
q.front = q.rear = 0; //头指针和尾指针置为零,队列为空
return OK;
}
//求循环队列的长度
int QueueLength(SqQueue q)
{
//return (q.rear-q.front+MAXQSIZE)%MAXQSIZE; //返回Q的元素个数,即队列长度
cout<
return OK;
}
//入队
Status EnQueue(SqQueue &q,QElemType e)//插入元素 e 为Q的新的队尾元素
{
if((q.rear+1)%MAXQSIZE==q.front) //尾指针在循环意义上加1后等于头指针,表明队满
return ERROR;
q.base[q.rear]=e; //新元素插入队尾
q.rear=(q.rear+1)%MAXQSIZE; //队尾指针加1
return OK;
}
//出队
Status DeQueue(SqQueue &q,QElemType &e)//删除 q 的队头元素,用 e 返回其值
{
if(q.front==q.rear) return ERROR;//队空
e=q.base[q.front]; //保存队头元素
q.front=(q.front+1)%MAXQSIZE;//队头指针加1
return OK;
}
//取队头元素
QElemType GetHead(SqQueue q)//返回 的队头元素,不修改队头指针
{
if(q.front!=q.rear) //队列非空
//return q.base[q.front];//返回队头元素的值,队头指针不变
cout<
return OK;
}
bool FullQueue(SqQueue &q)
{
if(q.rear==(q.front+1)%MAXQSIZE)
{
return 1;
}
else return 0;
}
bool EmptyQueue(SqQueue &q)
{
if(q.front==q.rear)
return 1;
else return 0;
}
//遍历队列
Status SqQueueTraver(SqQueue q,Status(*visit)(QElemType))
{
QElemType *b=&q.front;
QElemType *t=&q.rear-1;
while(b
visit(*b++);
return OK;
}
Status visit(QElemType c)
{
cout<
return OK;
}
int main()
{
QElemType e;
SqQueue q;
InitQueue(q);
int a;
cout<
cin>>a;
//if(a>MAXQSIZE) cout<
while(a--)
{
int n;
cin>>n;
EnQueue(q,n);
}
cout<
QueueLength(q);
cout<
cout<
GetHead(q);
cout<
DeQueue(q,e);
if(FullQueue(q)) cout<
if(EmptyQueue(q)) cout<
return 0;
}