易错:在EnQueue()和DeQueue()函数中要先取出队列的前端元素,在对rear或front进行更新,否则可能会错过第一个前端元素,导致输出缺少,程序出错。
int QueueLen(SqQueue Q)
{
return (Q->rear-Q->front+MAXQSIZE)%MAXQSIZE; //计算队列长度公式
}
int EnQueue(SqQueue &Q, Person e)
{
if(Q->rear+1)%MAXQSIZE==Q->front) //先判断队满
{
return ERROR;
}
Q->data[Q->rear]=e;
Q->rear=(Q->rear+1)%MAXQSIZE;
return OK;
}
int QueueEmpty(SqQueue &Q)
{
return (Q->front==Q->rear);
}
int DeQueue(SqQueue &Q, Person &e)
{
if(Q->front==Q->rear) //先判断队空
{
return ERROR;
}
e=Q->data[Q->front];
Q->front=(Q->front+1)%MAXQSIZE;
return OK;
}
void DancePartner(Person dancer[], int num)
{
int i;
for(i=0;i<num;i++)
{
if(dancer[i].sex=='M')
{
EnQueue(Mdancers,dancer[i]);
}else{
EnQueue(Fdancers,dancer[i]);
}
}
Person male,female; //用于储存出队的元素
while(!QueueEmpty(Mdancers)&&!QueueEmpty(Fdancers))
{
DeQueue(Fdancers,male);
DeQueue(Mdancers,female);
cout<<male.name<<" "<<female.name<<endl;
}
}