问题描述:
假设在周末舞会上,男士们和女士们进入舞厅时,各自排成一队。跳舞开始时,依次从男队和女队的队头各出一人配成舞伴。若两队初始人数不相同,则较长的那一队中未配对者等待下一轮舞曲。现要求写一算法模拟上述舞伴配对问题
- #include
- #define OVERFLOW -1
- #define Maxsize 100
- using namespace std;
- typedef struct {
- char name[20];
- char sex;
- }Dancer;
- typedef struct QNode{
- Dancer data;
- struct QNode* next;
- }QNode,*QuePtr;
- typedef struct {
- QuePtr front;
- QuePtr rear;
- }LinkQue;
- void InitQue(LinkQue& Q) {
- Q.front = Q.rear = new QNode;
- if (!Q.front)
- exit(OVERFLOW);
- Q.front->next = NULL;
- }
- bool QueEmpty(LinkQue& Q) {
- return(Q.front->next==NULL);
- }
- //出队
- void DeQue(LinkQue& Q,Dancer &d) {
- if (QueEmpty(Q))
- return;
- QuePtr p = Q.front->next;
- d = p->data;
- Q.front->next = p->next;
- delete p;
- }
- //入队
- void EnQue(LinkQue& Q,Dancer d) {
- QuePtr s = new QNode;
- s->data = d;
- Q.rear->next = s;
- Q.rear = s;
- s->next = NULL;
- }
- //取队头
- Dancer GetHead(LinkQue Q) {
- return(Q.front->next->data);
- }
- void DancingPartner(LinkQue &Mdancers,LinkQue &Fdancers,Dancer d[],int num) {
- Dancer p;
- for (int i = 0; i < num; i++) {
- p = d[i];
- if (p.sex == 'F')
- EnQue(Fdancers, p);
- else
- EnQue(Mdancers, p);
- }
- cout << "舞伴配对为 男/女:\n";
- //当男女舞者均不为空时,分别出队配对
- while (!QueEmpty(Mdancers) && !QueEmpty(Fdancers)) {
- DeQue(Mdancers, p);
- cout << p.name << " ";
- DeQue(Fdancers, p);
- cout << p.name << endl;
- }
- if (!QueEmpty(Fdancers)) {
- p = GetHead(Fdancers);
- cout << "下一轮第一个获得舞伴的是:" << p.name << endl;
- }
- else if (!QueEmpty(Mdancers)) {
- p = GetHead(Mdancers);
- cout << "下一轮第一个获得舞伴的是:" << p.name << endl;
- }
-
- }
- int main() {
- Dancer d[Maxsize];
- LinkQue Mdancers;
- LinkQue Fdancers;
- InitQue(Mdancers);
- InitQue(Fdancers);
- printf("请输入各个跳舞人的姓名和性别('F'表示女性,'M'表示男性):\n");
- for (int i = 0; i < 5; i++)
- {
- printf("请输入第%d个跳舞人的姓名和性别:\n", i + 1);
- cin >> d[i].name;
- cin>>d[i].sex;
- }
- DancingPartner(Mdancers, Fdancers, d, 5);
- }