实验目的:
熟悉队列的定义,队列的特点以及队列的基本操作。能够根据实际情况选择
合适的存储结构,解决实际问题。
实验要求:
算法完善,考虑时间复杂度。
实验内容:
利用循环队列模拟舞伴配对问题:
1、利用循环队列模拟舞伴配对问题。在舞会上,男、女各自排成一队。舞
会开始时。依次从男队和女队的队头各出一人配成舞伴。如果两队初始人数不等,
则较长的那一队中未配对者等待下一轮舞曲。
2、假设初始男、女人数及性别已经固定,舞会的轮数从键盘输入。
试模拟解决上述舞伴配对问题。
3、从屏幕输出每一轮舞伴配对名单,如果在该轮有未配对的,能够从屏幕
显示下一轮第一个出场的未配对者的姓名。
实验代码:
#include<iostream>
using namespace std;
#define MAXQSIZE 100
typedef struct {
char name[20]; //姓名
char sex; //性别,'F'表示女性,'M'表示男性
} Person;
//- - - - - 队列的顺序存储结构- - - - -
typedef struct {
Person data[MAXQSIZE];
int front; //头指针
int rear; //尾指针
} Queue;
typedef Queue* SqQueue;
SqQueue Mdancers, Fdancers;
int InitQueue(SqQueue& Q);
void DestroyQueue(SqQueue& q);
int QueueLen(SqQueue Q);//队列长度
int EnQueue(SqQueue& Q, Person e);//加入队列
int QueueEmpty(SqQueue& Q);//队列是否为空
int DeQueue(SqQueue& Q, Person& e);//出队列
void DancePartner(Person dancer[], int num); //配对舞伴
int main() {
int i,n;
Person dancer[MAXQSIZE];
cin >> n;
for (i = 0; i < n; i++) cin >> dancer[i].name >> dancer[i].sex;
InitQueue(Mdancers); //男士队列初始化
InitQueue(Fdancers); //女士队列初始化
cout << "结果如下" << endl;
DancePartner(dancer, n);
if (!QueueEmpty(Fdancers)) {
cout << "F:" << QueueLen(Fdancers);
}
else if (!QueueEmpty(Mdancers)) {
cout << "M:" << QueueLen(Mdancers);
}
DestroyQueue(Fdancers);
DestroyQueue(Mdancers);
return 0;
}
int InitQueue(SqQueue& Q) {//构造一个空队列Q
Q = new Queue;
if (!Q->data)
exit(-1);
Q->front = Q->rear = 0;
return 1;
}
void DestroyQueue(SqQueue& q)
{
delete q;
}
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 -1;
Q->data[Q->rear] = e;
Q->rear = (Q->rear + 1) % MAXQSIZE;
return 1;
};
//队列是否为空
int QueueEmpty(SqQueue& Q) {
if (Q->front == Q->rear)
return 1;
else
return 0;
};
//出队列
int DeQueue(SqQueue& Q, Person& e) {
if (Q->rear == Q->front)//队空
return false;
e = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXQSIZE;//队头指针+1
return 1;
};
//配对舞伴
void DancePartner(Person dancer[], int num) {
for (int i = 0; i < num; i++) {
if (dancer[i].sex == 'F') {
EnQueue(Fdancers, dancer[i]);
}
if (dancer[i].sex == 'M') {
EnQueue(Mdancers, dancer[i]);
}
}
while (!QueueEmpty(Fdancers) && !QueueEmpty(Mdancers)) {
Person p;
DeQueue(Fdancers, p);
cout << p.name << " ";
DeQueue(Mdancers, p);
cout << p.name << "\n";
}
};
实验结果截图: