6-1 另类循环队列
对带有元素数量个数变量count的队列
typedef int Position;
typedef struct QNode *PtrToQNode;
struct QNode {
ElementType *Data; /* 存储元素的数组 */
Position Front; /* 队列的头指针 */
int Count; /* 队列中元素个数 */
int MaxSize; /* 队列最大容量 */
};
typedef PtrToQNode Queue;
Queue CreateQueue( int MaxSize )
{
Queue Q = (Queue)malloc(sizeof(struct QNode));
Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
Q->Front = 0;
Q->Count = 0;
Q->MaxSize = MaxSize;
return Q;
}
bool AddQ( Queue Q, ElementType X ) {
if(Q->Count>=Q->MaxSize)
{
printf("Queue Full\n");
return false;
}
Q->Data[(Q->Front+Q->Count)%Q->MaxSize]=X;
//出队以后front增加,所以不能直接用 Q->Data[(Q->Front)%Q->MaxSize];
//同时用取余操作避免队列假满。
Q->Count++;
return true;
}
ElementType DeleteQ( Queue Q ) {
if(Q->Count==0)
{
printf("Queue Empty\n");
return ERROR;
}
ElementType temp= Q->Data[Q->Front];
Q->Front=(Q->Front+1)%Q->MaxSize;
--Q->Count;
return temp;
}