/*
问题:对于环形队列如果知道队头指针和队列中元素的个数。设计出这种
环形队列的基本操作。
分析:
队尾指针rear=(front+count)%MaxSize
队空条件:count==0.
队满条件:count==MaxSize。
*/
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 5
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];//存放队列中的元素
int front;//定义队头指针
int count;//定义元素个数
}QuType;//定义顺序队的类型

void InitQueue(QuType *&q)//初始化顺序队
{
q = (QuType *)malloc(sizeof(QuType));
q->front= 0;
q->count = 0;
}

void DestroyQueue(QuType *&q)//销毁顺序队
{
free(q);
}

bool QueueEmpty(QuType *q)//判断顺序队是否为空
{
return (q->count==0);
}

bool enQueue(QuType *&q,ElemType e)//入队
{
int rear;
if(q->count==MaxSize)//队满上溢出
return false;
else
{
rear=(q->front+q->count)%MaxSize;//求队尾位置
rear = (rear + 1)%MaxSize;
q->data[rear]=e;
q->count++;
return true;
}
}

bool deQueue(QuType *&q,ElemType &e)//出队
{
if(q->count==0)//对空下溢出
return false;

else
{
q->front = (q->front + 1)%MaxSize;
e = q->data[q->front];
q->count--;
return true ;
}

}
int main()
{
ElemType e;
QuType *q;
printf("环形队列基本运算如下:\n");
printf(" (1)初始化队列q\n");
InitQueue(q);
printf(" (2)依次进队列元素a,b,c\n");
if (!enQueue(q,'a')) printf("\t提示:队满,不能进队\n");
if (!enQueue(q,'b')) printf("\t提示:队满,不能进队\n");
if (!enQueue(q,'c')) printf("\t提示:队满,不能进队\n");
printf(" (3)队列为%s\n",(QueueEmpty(q)?"空":"非空"));
if (deQueue(q,e)==0)
printf("队空,不能出队\n");
else
printf(" (4)出队一个元素%c\n",e);
printf(" (5)依次进队列元素d,e,f\n");
if (!enQueue(q,'d')) printf("\t提示:队满,不能进队\n");
if (!enQueue(q,'e')) printf("\t提示:队满,不能进队\n");
if (!enQueue(q,'f')) printf("\t提示:队满,不能进队\n");
printf(" (6)出队列序列:");
while (!QueueEmpty(q))
{ deQueue(q,e);
printf("%c ",e);
}
printf("\n");
printf(" (7)释放队列\n");
DestroyQueue(q);
return 0;
}

运行结果:

特殊环形队列基本操作_环形队列