/*牺牲一个单元来区分队空队满*/
#include<stdio.h>
#define MaxSize 10
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int front,rear;
}SqQueue;
bool InitQueue(SqQueue &q)
{
q.front=q.rear=0; //初始化队头队尾指针
return true;
}
bool EmptyQueue(SqQueue q)
{
if(q.rear==q.front) //队空的条件:首尾指针指向同一地址
return true;
return false;
}
bool EnQueue(SqQueue &q,ElemType e)
{
if((q.rear+1)%MaxSize==q.front) //队满的条件(牺牲一个单元判断队满)
return false;
q.data[q.rear]=e;
q.rear=(q.rear+1)%MaxSize; //队尾指针加一取模
return true;
}
bool OutQueue(SqQueue &q,ElemType &e)
{
if(q.rear==q.front) //判空
return false;
e=q.data[q.front];
q.front=(q.front+1)%MaxSize; //队首指针加一取模
return true;
}
bool HeadQueue(SqQueue q,ElemType &e)
{
if(q.rear==q.front)
return false;
e=q.data[q.front];
return true;
}
void main()
{
SqQueue q;
InitQueue(q);
ElemType e;
printf("The Queue is %s
",(EmptyQueue(q)?"Empty!":"UnEmpty!"));
EnQueue(q,'a');
EnQueue(q,'b');
EnQueue(q,'c');
HeadQueue(q,e);
printf("Queue_Head=%c
",e);
OutQueue(q,e);
HeadQueue(q,e);
printf("Queue_Head=%c
",e);
}