[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;
    }
}

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值