/////////////////////////////////////////////////////////// 
//--------------------------------------------------------- 
//            循环队列存储结构及基本操作 
//--------------------------------------------------------- 
/////////////////////////////////////////////////////////// 

#include<stdio.h> 
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
#include<ctype.h>

//以下为函数运行结果状态代码 
#define TRUE 1
#define FALSE 0
#define OK 1 
#define ERROR 0 
#define INFEASIBLE -1 
#define OVERFLOW -2 

#define MAXQSIZE 100  //最大队列长度 

typedef int Status; //函数类型，其值为函数结果状态代码
typedef int QElemType; //数据类型定位整型 
typedef struct {
	QElemType * base;//初始化的动态分配存储空间 
	int front;//头指针，若队列不空，指向队列头元素 
	int rear;//尾指针，若队列不空，指向队列尾元素的下一个位置
}SqQueue; 

//-------------基本操作的函数原型说明----------------
Status InitQueue(SqQueue &Q);
Status DestroyQueue(SqQueue &Q);
Status ClearQueue(SqQueue &Q);
Status QueueEmpty(SqQueue Q);
int QueueLength(SqQueue Q);
Status GetHead(SqQueue Q,QElemType &e);
Status EnQueue(SqQueue &Q,QElemType e);
Status DeQueue(SqQueue &Q,QElemType &e);
Status QueueTravserse(SqQueue Q);


//-----------基本操作的算法----------------
Status InitQueue(SqQueue &Q){
	//构造一个空队列
	Q.base=(QElemType*)malloc(MAXQSIZE*sizeof(QElemType));
	if(!Q.base) exit(OVERFLOW);//存储分配失败
	Q.front=0;
	Q.rear=0;
	return OK;
}

Status DestroyQueue(SqQueue &Q){
	//
	if(Q.base==NULL) return INFEASIBLE;//队列不存在
	int i;
	for(i=0;i<MAXQSIZE;i++){
		free(Q.base);
		Q.base++;
	}
	Q.base=NULL;
	return OK;
}

Status ClearQueue(SqQueue &Q){
	//
	if(Q.base==NULL) return INFEASIBLE;//队列不存在
	int i;
	for(i=0;i<MAXQSIZE;i++){
	Q.base[i]=0;
	}
	Q.front=0;
	Q.rear=0;
	return OK;
}

Status QueueEmpty(SqQueue Q){
	//
	if(Q.base==NULL) return INFEASIBLE;//队列不存在
	if(Q.front==Q.rear) return TRUE;
	else return FALSE;
}

int QueueLength(SqQueue Q){
	//
	if(Q.base==NULL) return INFEASIBLE;//队列不存在
	return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}

Status GetHead(SqQueue Q,QElemType &e){
	//
	if(Q.base==NULL) return INFEASIBLE;//队列不存在
	if(Q.rear==Q.front) return OVERFLOW;//队列为空
	e=Q.base[Q.front];
	return OK;
}

Status EnQueue(SqQueue &Q,QElemType e){
	//
	if(Q.base==NULL) return INFEASIBLE;//队列不存在
	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.base==NULL) return INFEASIBLE;//队列不存在
	if(Q.front==Q.rear) return ERROR;//队列为空
	e=Q.base[Q.front];
	Q.front=(Q.front+1)%MAXQSIZE;
	return OK;
}

