[C语言、C++]数据结构作业:用队列实现舞伴问题

舞伴问题:

某学校的新年晚会上,男同学和女同学需要组成舞伴跳舞,

现需要把所有人分成男女两队,然后依次出队一个男同学和一个女同学组成舞伴,

打印配对的结果,和最后剩下没有舞伴的同学的性别和姓名 

 

 

#include <iostream>
using namespace std;
struct person {
    char name; //姓名
    char sex; //性别
};
typedef person ElemType; //元素的数据类型
struct QueueNode { //队列结点定义
    ElemType data;
    QueueNode* next;
};
struct LinkQueue { //队列结构定义
    QueueNode* rear,
        * front; //队尾与队头指针
};
void InitQueue(LinkQueue& Q) {
    Q.rear = Q.front = NULL;
}
bool IsEmpty(const LinkQueue& Q) {
    return Q.front == NULL;
}
bool getFront(const LinkQueue& Q, ElemType& e) {
    if (IsEmpty(Q))
        return false;
    e = Q.front->data;
    return true;
}
int EnQueue(LinkQueue& Q, ElemType e) {
    QueueNode* s = new QueueNode;
    s->data = e; s->next = NULL;//创建结点
    if (!Q.front) //空
        Q.front = Q.rear = s; //f,r指向首元节点
    else { //不空
        Q.rear->next = s; //尾插
        Q.rear = s;
    }
    return 1;
}
int DeQueue(LinkQueue& Q, ElemType& e) {
    //删去队头结点,并返回队头元素的值
    if (IsEmpty(Q)) return 0;//判队空
    QueueNode* q = Q.front;
    e = q->data; //保存队头的值
    Q.front = Q.front->next; //新队头
    if (Q.front == NULL) Q.rear = NULL;
    delete q;
    return 1;
}
int main(){
    LinkQueue MQ, FQ; //男、女队列
    InitQueue(MQ), InitQueue(FQ); //初始为空
    person dancer[10] = { {'a','M'},{'b','M'}, {'c','F'}, {'d','F'}, {'e','F'}, {'f','F'}, {'g','F'}, {'h','F'}, {'i','M'}, {'j','M'} };//跳舞人
    for (int i = 0; i < 10; i++) {//形成队列
        if (dancer[i].sex == 'M') EnQueue(MQ, dancer[i]);
        else EnQueue(FQ, dancer[i]);
    }
    while (!IsEmpty(MQ) && !IsEmpty(FQ)) {
        person p;
        DeQueue(MQ, p); cout << p.name << " ";
        DeQueue(FQ, p); cout << p.name << endl;
    }
    if (!IsEmpty(MQ)) {
        person e;
        getFront(MQ, e); cout << "first M : " << e.name;
    }
    else if (!IsEmpty(FQ)) {
        person e;
        getFront(FQ, e); cout << "first F : " << e.name;
    }
}


版权声明:本文为ZDEWBYE原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。