舞伴问题:先入队的男士和先入队的女士先出队配成舞伴。
设置两个队列分别存放男士和女士入队者;
舞会开始时,依次将两队当前的队头元素出队来配成舞伴,直至某队列变空为止。
此时,若某队仍有等待配对者,则输出此队列中排在队头的等待者的姓名,此人将是下一轮舞曲开始时第一个可获得舞伴的人。
请编写程序,利用顺序队或链队实现舞伴问题
#include <iostream>
#define ok 1
#define error 0
using namespace std;
//typedef char QElemType;
typedef int status;
//------------定义-------------
typedef struct
{
char name[20];
char sex;
}Person, QElemType;
typedef struct QNode
{
QElemType data;
struct QNode *next;
}QNode, *QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
LinkQueue Mdancers ;
LinkQueue Fdancers ;
//---------------声明-------------------
status InitQueue (LinkQueue &Q);
status EnQueue (LinkQueue &Q ,Person e);
int DeQueue (LinkQueue &Q, Person &e);
Person GetHead (LinkQueue Q);
status IsEmptyQueue (LinkQueue Q);
void DancePartner(Person dancer[], int num);
int main() {
int n;
Person dancers[5];
InitQueue(Fdancers);
InitQueue(Mdancers);
cout << "多少人参加舞会:" << endl;
cin >> n;
for (int i = 1; i <= n; i++) {
cout << "请输入第" << i << "个人的姓名和性别<F或M>: " << endl ;
cin >> dancers[i].name >> dancers[i].sex;
}
DancePartner(dancers, 5);
return 0;
}
//---------------初始化------------------
status InitQueue (LinkQueue &Q)
{ //构造一个空队列
Q.front = Q.rear = new QNode; //生成新结点作为头结点,队头和队尾指针指向此结点
Q.front->next = NULL; //头结点的指针域置空
return ok;
}
//---------------判空---------------------
status IsEmptyQueue (LinkQueue Q)
{
if (Q.front == Q.rear) //队空
return ok;
else
return error;
}
//---------------入队-------------------
status EnQueue (LinkQueue &Q , Person e)
{ //插入新元素为Q的新的队尾元素
QNode *p = new QNode; //生成新结点p
p->data = e; //将新结点数据域置为e
p->next = NULL;
Q.rear->next = p; //将新结点插入到队尾
Q.rear = p; //修改队尾指针
return ok;
}
//---------------出队--------------------
status DeQueue (LinkQueue &Q, Person &e)
{ //删除Q的队头元素,用e返回其值
if (Q.front == Q.rear) //判断队空
return error;
QNode *p = Q.front->next; //p指向队头元素
e = p->data; //e保存队头元素的值
Q.front->next = p->next; //修改头结点的指针域
if (Q.rear == p) //如果p已经到达队尾了,最后一个元素被删除,队尾指针指向头结点
Q.rear = Q.front;
delete p; //释放原队头元素的空间
return ok;
}
//--------------取队头元素---------------
Person GetHead (LinkQueue Q)
{
if (Q.front != Q.rear) //队不空时
return Q.front->next->data; //返回队头元素,不修改队头指针
}
//--------------舞伴问题--------------
void DancePartner (Person dancer[], int num)
{ //结构体数组dancer中存放跳舞的男女,num是跳舞的人数
Person p ;
InitQueue(Mdancers); //男士队列初始化
InitQueue(Fdancers); //女士队列初始化
for (int i = 1 ; i <= num; i++)
{
p = dancer[i];
if (p.sex == 'F')
EnQueue(Fdancers, p); //插入女队
else
EnQueue(Mdancers, p); //插入男队
}
cout << "组合的舞伴是:" << endl;
while (!IsEmptyQueue(Fdancers) && !IsEmptyQueue(Mdancers))
{ //依次输出男女舞伴的姓名
DeQueue(Fdancers, p); //女士出队
cout << p.name << ' ' ; //输出出队女士的姓名
DeQueue(Mdancers, p); //男士出队
cout << p.name << endl ; //输出出队男士的姓名
}
if (!IsEmptyQueue(Fdancers))
{
p = GetHead(Fdancers); //女士队列非空,输出队头女士的姓名
cout << "下一曲第一个获得舞伴的女士是:" << p.name << endl;
}
// else if (!IsEmptyQueue(Mdancers))
// {
// p = GetHead(Mdancers); //男士队列非空,输出队头男士的姓名
// cout << "下一曲第一个获得舞伴的男士是:" << p.name ;
// }
}
链队实现舞伴问题
最新推荐文章于 2022-11-13 14:22:23 发布