欢迎加qq群:453398542 学习讨论,会定期分享资料课程,解答问题。
循环队列的应用——舞伴配对问题:在舞会上,男、女各自排成一队。舞会开始时,依次从男队和女队的队头各出一人配成舞伴。如果两队初始人数不等,则较长的那一队中未配对者等待下一轮舞曲。假设初始男、女人数及性别已经固定,舞会的轮数从键盘输入。试模拟解决上述舞伴配对问题。要求:从屏幕输出每一轮舞伴配对名单,如果在该轮有未配对的,能够从屏幕显示下一轮第一个出场的未配对者的姓名。
#include<stdio.h>
#include<stdlib.h>
#define SIZE 100 //最大队列长度
typedef struct {
int *base; //初始化动态分配空间
int front;
int rear;
} SqQueue;
void InitQueue(SqQueue &Q){
//构造一个空队列
Q.base=(int *)malloc(SIZE*sizeof(int));
if (!Q.base) exit(0);
else
Q.front=Q.rear=0;
}
int QueueLength(SqQueue Q){
//求队列的长度
return (Q.rear-Q.front+SIZE)%SIZE;
}
int QueueEmpty(SqQueue Q){
//判空
if (Q.rear==Q.front) return 1;
else
return 0;
}
void EnQueue(SqQueue &Q,int e){
//插入元素e为Q的新的队尾元素
if ((Q.rear+1)%SIZE==Q.front)
exit(0);
else
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1)%SIZE;
}
void DeQueue(SqQueue &Q,int &e){
// 删除Q的队头元素, 并用e返回其值
if ((Q.rear+1)%SIZE==Q.front)
exit(0);
else
e=Q.base[Q.front];
Q.front=(Q.front+1)%SIZE;
}
void GetHead(SqQueue Q,int &e){
// 取Q的队头元素, 并用e返回其值
if ((Q.rear+1)%SIZE==Q.front)
exit(0);
else
e=Q.base[Q.front];
}
void DancingPartner(SqQueue &M,SqQueue &W){
//舞伴配对
int i,j,n,min,len1,len2,man,woman,dancer;
len1=QueueLength(M);
len2=QueueLength(W);
min=len1<len2?len1:len2;
printf("请输入舞会的轮数:");
scanf("%d",&n);
for(i=1;i<=n;i++){
printf("第%d轮舞伴跳舞:\n",i);
for(j=0;j<min;j++){
DeQueue(M,man); DeQueue(W,woman);
printf("%d<-->%d\n",man,woman);
EnQueue(M,man); EnQueue(W,woman);
}
if(len1>len2)
GetHead(M,dancer);
else
GetHead(W,dancer);
printf("下一个出场的是:%d\n",dancer);
}
}
int main(){
int name;
SqQueue M,W;
InitQueue(M); InitQueue(W);
printf("男队:(0表示结束)\n");
scanf("%d",&name);
while(name){
EnQueue(M,name);
scanf("%d",&name);
}
printf("女队:(0表示结束)\n");
scanf("%d",&name);
while(name){
EnQueue(W,name);
scanf("%d",&name);
}
DancingPartner(M,W);
return 0;
}