/************************************************************************/
/* 队列的环式顺序实现 */
/************************************************************************/
#include <STDIO.H>
#include <STDLIB.H>
typedef int QElementType;
typedef int status;
#define _ERROR 0
#define _OK 1
#define MAXQSIZE 10
/*队列的数据抽象*/
typedef struct
{
QElementType *base;
int front;//队列头指针
int rear;//队列尾指针
} SqQueue;
/*队列初始化函数*/
status InitQueue(SqQueue &Q)
{
Q.base = (QElementType*)malloc(MAXQSIZE*sizeof(QElementType));
if(Q.base==NULL)
return _ERROR;
Q.front = Q.rear = 0;
return _OK;
}
/*判断队列是否为空*/
bool IsEmpty(SqQueue Q)
{
return Q.front==Q.rear;
}
/*判断队列是否已满,这里我们牺牲一个空间,为甚么?你懂的*/
bool IsFull(SqQueue Q)
{
return ((Q.rear+1)%MAXQSIZE)==Q.front;
}
/*获取队列长度*/
int QueueLength(SqQueue Q)
{
return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}
/*入队列*/
status InQueue(SqQueue &Q,QElementType e)
{
//判断队列是否已满
if(IsFull(Q))
return _ERROR;
Q.base[Q.rear]=e;
Q.rear = (Q.rear+1)%MAXQSIZE;
return _OK;
}
/*出队列*/
status OutQueue(SqQueue &Q,QElementType &e)
{
/*判断队列是否为空*/
if(IsEmpty(Q))
return _ERROR;
e = Q.base[Q.front];
Q.front = (Q.front + 1)%MAXQSIZE;
return _OK;
}
/*打印队列中的元素*/
void PrintQueue(SqQueue Q)
{
for (int i = Q.front;i%MAXQSIZE<Q.rear;i++)
{
printf("%d\n",Q.base[i]);
}
}
void main()
{
/*初始化队列*/
SqQueue Q;
InitQueue(Q);
printf("入队列测试:\n");
/*入队列测试*/
InQueue(Q,1);
InQueue(Q,2);
InQueue(Q,3);
InQueue(Q,4);
InQueue(Q,5);
InQueue(Q,6);
InQueue(Q,7);
InQueue(Q,8);
InQueue(Q,9);
PrintQueue(Q);
printf("溢出测试:\n");
/*溢出测试*/
InQueue(Q,10);
PrintQueue(Q);
printf("出队列测试:\n");
/*出队列测试*/
QElementType e;
OutQueue(Q,e);
printf("%d\n",e);
OutQueue(Q,e);
printf("%d\n",e);
printf("长度测试:\n");
/*长度测试*/
printf("%d\n",QueueLength(Q));
}
/*实验结果如下*/