#include<stdlib.h>
#include<stdio.h>
#define MinQueueSize 5
typedef int ElementType ;
typedef struct QueueRecord
{
int Capacity; //域 ,数组最大容量
int Front; //头指针
int Rear; //尾指针
int Size; //数组大小
ElementType *Array; //数组
}*Queue;
int IsEmpty(Queue Q);
int IsFull(Queue Q);
Queue CreateQueue(int MaxElements);
void DisposeQueue(Queue Q);
void MakeEmpty(Queue Q);
void EnQueue(ElementType x,Queue Q); //入对
ElementType Front(Queue Q);
void DeQueue(Queue Q); //出对
ElementType FrontAndDequeue(Queue Q); //取得头元素并出对
int IsEmpty(Queue Q) //判断是否为空
{
return Q->Size==0;
}
int IsFull(Queue Q)
{
return Q->Size == Q->Capacity;
}
void MakeEmpty(Queue Q) //构造空队列
{
Q->Size=0;
Q->Front=1; //当为空时 Rear=Front-1
Q->Rear=0;
}
Queue CreateQueue(int MaxElements)
{
Queue Q;
if(MaxElements < MinQueueSize)
{
printf("Queue Size is too small\n");
exit(1);
}
Q=malloc(sizeof(struct QueueRecord));
if(Q == NULL)
{
printf("Out of space !!!");
exit(1);
}
Q->Array=malloc(sizeof(ElementType)*MaxElements);
if(Q->Array == NULL)
{
printf("Out of space !!!");
exit(1);
}
Q->Capacity=MaxElements;
MakeEmpty(Q);
return Q;
}
static int Succ(int Value,Queue Q) //申请一个数组空间,
{ //当数组达到最大时循环
if(++Value == Q->Capacity) //达到最大值时尾指针
Value=0;
return Value;
}
void EnQueue(ElementType x,Queue Q)
{
if(IsFull(Q))
{
printf("Full Queue \n");
exit(1);
}
Q->Size++;
Q->Rear=Succ(Q->Rear,Q);
Q->Array[Q->Rear]=x;
}
void DeQueue(Queue Q)
{
if(Q == NULL)
{
printf("Empty queue \n");
exit(1);
}
else
{
Q->Size--;
Q->Front=Succ(Q->Front,Q);
}
}
void DisposeQueue(Queue Q)
{
if(Q!=NULL)
{
free(Q->Array);
free(Q);
}
}
ElementType Front(Queue Q)
{
if(!IsEmpty(Q))
{
return Q->Array[Q->Front];
}
printf("Empty Queue \n");
return 0;
}
ElementType FrontAndDequeue(Queue Q)
{
ElementType x=0;
if(IsEmpty(Q))
{
printf("Empty queue \n");
exit(1);
}
else
{
Q->Size--;
x=Q->Array[Q->Front];
Q->Front=Succ(Q->Front,Q);
}
return x;
}
int main()
{
Queue Q;
int i;
Q=CreateQueue(12);
for(i=0;i<10;i++)
EnQueue(i,Q);
while(!IsEmpty(Q))
{
printf("%d ",Front(Q));
DeQueue(Q);
}
printf("\n");
for(i=0;i<10;i+=2)
EnQueue(i,Q);
while(!IsEmpty(Q))
{
printf("%d ",Front(Q));
DeQueue(Q);
}
printf("\n");
DisposeQueue(Q);
return 0;
}