栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

PTA 6-3 舞伴问题 (20 分) C语言

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PTA 6-3 舞伴问题 (20 分) C语言

 

坑点!!!

1.提交时一定要提交完整的函数,不要只提交DancerPartner函数中的代码

2.当男士或者女士多余的时候,只输出没有配对的队头元素的姓名

3.用FrontQueue_link取出队列的元素后,不要忘记用DeQueue_link删除队列的头元素。

4.当输出配对的舞伴之后,要空一行再输出没有配对的


题目要求

假设男士和女士的记录存放在一个数组中,设计算法实现舞伴配对,要求输出配对的舞伴,并输出没有配对的队头元素的姓名。其中 dancer[]是存放男士和女士信息的数组,num是数组大小。

分析代码

对所给的代码加了注释做解析

#include
#include

//结构体存放姓名和性别
typedef struct {
    char name[20];
    char sex;
} DataType;
//链表
struct Node {
    DataType      data;
    struct Node*  next;
};
typedef struct Node  *PNode;
//队列
struct Queue
{
    PNode        f;
    PNode        r;
};
typedef struct Queue *linkQueue;

//创建一个空队列
linkQueue  SetNullQueue_link()
{
    linkQueue lqueue;
    lqueue = (linkQueue)malloc(sizeof(struct Queue));
    if (lqueue != NULL)
    {
        lqueue->f = NULL;
        lqueue->r = NULL;
    }
    else
        printf("Alloc failure! n");//创建失败
    return  lqueue;
}

//队列是否为空
int IsNullQueue_link(linkQueue lqueue)
{
    return (lqueue->f == NULL);
}

//向队列中添加元素
void EnQueue_link(linkQueue lqueue, DataType x)
{
    PNode  p;
    p = (PNode)malloc(sizeof(struct Node));
    if (p == NULL)
        printf("Alloc failure!");
    else {
        p->data = x;
        p->next = NULL;
        if (lqueue->f == NULL)
        {
            lqueue->f = p;
            lqueue->r = p;
        }
        else
        {
            lqueue->r->next = p;
            lqueue->r = p;
        }
    }
}

//删除队列的头元素
void DeQueue_link(linkQueue lqueue)
{
    struct Node  * p;
    //判断是否为空
    if (lqueue->f == NULL)
        printf("It is empty queue!n ");
    else
    {
        p = lqueue->f;
        lqueue->f = lqueue->f->next;
        free(p);
    }
}

//拿到队列的头元素
DataType  FrontQueue_link(linkQueue lqueue)
{
    //判断队列是否为空
    if (lqueue->f == NULL)
    {
        printf("It is empty queue!n");
    }
    else
        return (lqueue->f->data);
}

void DancePartner(DataType dancer[], int num)
{
            
    
}

int main()
{
    DataType dancer[9];
    for (int i = 0; i < 9; i++)
    scanf("%s %c", dancer[i].name, &dancer[i].sex);
    DancePartner(dancer, 9);
    return 0;
}

答案

解析见注释

void DancePartner(DataType dancer[], int num)
{
            
    //用来存放性别为M的dancer的队列
    linkQueue Mdancer=SetNullQueue_link();
    //用来存放性别为F的dancer的队列
    linkQueue Fdancer=SetNullQueue_link();
    //遍历所给的dance数据
    for(int i=0;i 

点点赞吧~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/767305.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号