//库函数头文件包含
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
//函数状态码的定义
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXQSIZE 100
typedef int Status;
typedef int QElemType;
//-----循环队列————队列的顺序存储结构-----------
typedef struct SqQueue{
QElemType *base;
int Front;
int Rear;
}SqQueue;
//----------循环队列的基本操作的实现-----------
//构造一个空队列Q
Status InitQueue(SqQueue &Q){
Q.base = (QElemType *)malloc(MAXQSIZE * sizeof(QElemType));
if(!Q.base)
exit(OVERFLOW); //储存分配失败
Q.Front = Q.Rear = 0;
return OK;
}
//销毁队列
Status DestroyQueue(SqQueue &Q){
free(Q.base);
Q.Front = Q.Rear = 0;
return OK;
}
//清空队列
Status ClearQueue(SqQueue &Q){
Q.Front = Q.Rear = 0; //此处不一定非得等于0,等于其它的也可以,只要保证Q.Front = Q.Rear并且不超过最大容量就行
return OK;
}
//返回队列的长度
int QueueLength(SqQueue Q){
return (Q.Rear - Q.Front + MAXQSIZE) % MAXQSIZE;
}
//返回队头元素
Status GetHead(SqQueue Q, QElemType &e){
if(Q.Rear == Q.Front)
return ERROR;
e = Q.base[Q.Front];
return OK;
}
//判断队列是否为空
Status Is_QueueEmpty(SqQueue Q){
if(Q.Rear == Q.Front)
return TRUE;
return FALSE;
}
//入队
Status EnQueue(SqQueue &Q, QElemType e){
if((Q.Rear + 1) % MAXQSIZE == Q.Front) //如果队列已经满了,就不再添加新元素
return ERROR;
Q.base[Q.Rear] = e;
Q.Rear = (Q.Rear + 1) % MAXQSIZE; //加就可能会越界,因此要取余数
return OK;
}
//出队
Status DeQueue(SqQueue &Q, QElemType &e){
if(Q.Rear == Q.Front)
return ERROR;
e = Q.base[Q.Front];
Q.Front = (Q.Front + 1) % MAXQSIZE;
return OK;
}
//visit()函数
Status Print(QElemType e){
printf("%d ", e);
return OK;
}
//队列的遍历
Status QueueTraverse(SqQueue Q, Status (*visit)(QElemType)){
for(int i = Q.Front; i != Q.Rear; i = (i + 1) % MAXQSIZE){
if(!visit(Q.base[i]))
return ERROR;
}
return OK;
}
//主函数
int main(){
SqQueue Q;
QElemType a;
InitQueue(Q);
printf("输入5个数:\n");
for(int i = 0; i < 5; ++i){
scanf("%d", &a);
EnQueue(Q, a);
}
printf("遍历队列:\n");
QueueTraverse(Q, Print);
DeQueue(Q, a);
printf("\n执行一次出队操作的结果:\n");
QueueTraverse(Q, Print);
printf("\n获得队列长度操作的结果:\n%d", QueueLength(Q));
GetHead(Q, a);
printf("\n获得队头元素操作的结果:\n%d", a);
printf("\n判断队列是否为空:\n");
if(Is_QueueEmpty(Q))
printf("YES");
else
printf("NO");
printf("\n执行清空队列操作后队列是否为空:\n");
ClearQueue(Q);
if(Is_QueueEmpty(Q))
printf("YES");
else
printf("NO");
DestroyQueue(Q);
return 0;
}
下面是对代码的简单测试结果: