#include <iostream>
using namespace std;
#define QElemType int
#define OK 1
#define FALSE 0
#define TRUE 1
#define ERROR 0
// 循环队列,队列的顺序存储结构
#define MAXQSIZE 100 //最大队列长度
typedef struct
{
QElemType *base; //初始化的动态分配存储空间
int Front; //头指针,若队列不空,指向队列头元素
int Rear; //尾指针,若队列不空,指向队列尾元素的下一个位置
}SqQueue;
//构造一个空队列Q
int InitQueue(SqQueue &Q)
{
Q.base = (QElemType *)malloc(MAXQSIZE*sizeof(QElemType));
if(!Q.base)
exit(OVERFLOW);
Q.Front = Q.Rear = 0;
return OK;
}
//插入元素e为Q的新的队列元素
int 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;
}
//输出队列Q中的元素
void QueueTraverse(SqQueue Q)
{
if(Q.Front == Q.Rear)
cout << "队列为空" << endl;
while(Q.Front != Q.Rear)
{
cout << Q.base[Q.Front ]<<" ";
Q.Front = (++Q.Front) % MAXQSIZE;
}
cout << endl;
}
//若队列为空,则返回TRUE
//否则,返回FALSE
int QueueEmpty(SqQueue Q)
{
if(Q.Rear == Q.Front)
return TRUE;
else
return FALSE;
}
//得到队列Q的长度
int QueueLength(SqQueue Q)
{
int i = 0;
while(Q.Front != Q.Rear)
{
++i;
++Q.Front;
}
return i;
}
//若队列不空,用e返回队头指针
void GetHead(SqQueue Q,QElemType &e)
{
if(Q.Front == Q.Rear)
cout << "队列空!" <<endl;
e = Q.base[Q.Front];
}
//若队列不空,则用e返回Q的队头元素
void DeQueue(SqQueue &Q,QElemType &e)
{
if(Q.Front == Q.Rear)
cout << "队列空!" << endl;
e = Q.base[Q.Front];
Q.Front = (Q.Front+1) % MAXQSIZE;
}
//销毁队列Q,Q不再存在
void DestroyQueue(SqQueue &Q)
{
if(Q.Front != Q.Rear)
{
free(Q.base);
Q.Front++;
}
cout << "队列不再存在!"<< endl;
}
//将队列Q清为空队列
void ClearQueue(SqQueue &Q)
{
while(Q.Front != Q.Rear)
{
Q.base[Q.Front] = NULL;
Q.Front++;
}
Q.Front = Q.Rear = 0;
}
void main()
{
SqQueue Q;
InitQueue(Q);
QElemType a = 10;
EnQueue(Q,a);
QElemType b = 11;
EnQueue(Q,b);
QueueTraverse(Q);
cout << QueueEmpty(Q) << endl;
//cout << QueueLength(Q) << endl;
//QElemType c;
//GetHead(Q,c);
//cout << c << endl;
//QElemType d;
//DeQueue(Q,d);
//cout << d << endl;
//QueueTraverse(Q);
//DestroyQueue(Q);
//QueueTraverse(Q);
ClearQueue(Q);
//QueueTraverse(Q);
system("pause");
}