如果用一个循环数组表示队列,并且只设队列头指针Front,不设尾指针Rear,而是另设Count记录队列中元素个数。请编写算法实现队列的入队和出队操作。
函数接口定义:
bool AddQ( Queue Q, ElementType X );
ElementType DeleteQ( Queue Q );
其中Queue结构定义如下:
typedef int Position;
typedef struct QNode *PtrToQNode;
struct QNode {
ElementType Data; / 存储元素的数组 /
Position Front; / 队列的头指针 /
int Count; / 队列中元素个数 /
int MaxSize; / 队列最大容量 */
};
typedef PtrToQNode Queue;
注意:如果队列已满,AddQ函数必须输出“Queue Full”并且返回false;如果队列是空的,则DeleteQ函数必须输出“Queue Empty”,并且返回ERROR。
代码:
bool AddQ( Queue Q, ElementType X )//入队列
{
if(Q->Count == Q->MaxSize)//若队列已满
{
printf("Queue Full\n");
return false;
}
else//若队列未满
{
Q->Data[(Q->Front + Q->Count)%Q->MaxSize] = X;//(Q->Front + Q->Count)/Q->MaxSize 表示队尾元素的下一个元素的下标
Q->Count++;//元素数加1
}
return true;
}
ElementType DeleteQ( Queue Q )//出队列
{
ElementType e;
if(0 == Q->Count)//队空
{
printf("Queue Empty\n");
return ERROR;
}
else
{
e = Q->Data[Q->Front];//先取队首元素
Q->Front = (Q->Front + 1)%Q->MaxSize;//头指针前移
Q->Count--;//元素数减一
}
return e;
}