数据结构——舞伴问题

张宇杰 2022-10-28 16:17:16
//库函数的引用 
#include <stdio.h>
#include <stdlib.h>
//宏定义
#define MAXQSIZE 100 
#define OVERFLOW -2
#define OK 1 
#define ERROR 0 

//数据类型的重命名,定义
typedef struct 
{
	char name[20];
	char sex;
}QElemType;  
typedef int Status; 
typedef struct  
{
	QElemType *base;
	int front;
	int rear;
}SqQueue;

//函数声明 
Status InitQueue(SqQueue &Q);
Status EnQueue(SqQueue &Q, QElemType e);
Status DeQueue(SqQueue &Q, QElemType &e);
int QueueEmpty(SqQueue Q);
QElemType GetHead(SqQueue Q);
void DancePartner(QElemType dancer[],int num);



//主函数 
int main(int argc, char *argv[])
{
	SqQueue Q;
	QElemType e; 
	QElemType dancer[5] = {{"liLei",'F'},
						   {"ZhangJie",'F'},
						   {"liMei",'M'},
						   {"luLin",'F'},
						   {"WangLei",'M'},
						  }; 
	if( OK == InitQueue(Q))
		printf("初始化成功!\n");
	/*for( i = 0; i < 5; i ++)
	{
		scanf("%s", dancer[i]);
		scanf("%c", dancer[i]);
	}*/
	DancePartner(dancer, 5);
	return 0;
}

/*----------------------自定义函数---------------------*/

Status InitQueue(SqQueue &Q)
{
	Q.base = new QElemType[MAXQSIZE];
	if(!Q.base)
		exit(OVERFLOW);
	Q.front = 0;
	Q.rear = 0;
	return OK;	
}

Status EnQueue(SqQueue &Q, QElemType e)
{
	//判满 
	if((Q.rear + 1) % MAXQSIZE == Q.front)
		return 	ERROR;
	//入队
	Q.base[Q.rear] = e;
	//rear ++
	Q.rear = (Q.rear + 1) % MAXQSIZE;
	return OK; 
}

Status DeQueue(SqQueue &Q, QElemType &e)
{
	//判空 
	if(Q.rear  == Q.front)
		return 	ERROR;
	//出队
	e = Q.base[Q.front];
	//front ++
	Q.front = (Q.front + 1) % MAXQSIZE;
	return OK; 
}

int QueueEmpty(SqQueue Q)
{
	if(Q.front == Q.rear)
		return 1;
	else
		return 0;
}

QElemType GetHead(SqQueue Q)
{
	if(!QueueEmpty(Q))
		return Q.base[Q.front];
}

void DancePartner(QElemType dancer[],int num)
{//结构数组dancer中存放跳舞的男女,num是跳舞的人数。
	SqQueue Mdancers, Fdancers;
	QElemType p;
	InitQueue(Mdancers);   //男士队列初始化
	InitQueue(Fdancers);   //女士队列初始化
	for(int i = 0; i < num; i++)    //依次将跳舞者根据其性别人队
	{   
		p = dancer[i];
		if( p.sex == 'F') EnQueue(Fdancers, p); //插入女队
		else              EnQueue(Mdancers, p); //插人男队
	}
		printf("The dancing partners are:\n");
	while(!QueueEmpty(Fdancers) && !QueueEmpty(Mdancers))
	{
		//依次输出男女舞伴的姓名
		DeQueue(Fdancers, p);   //女士出队
		printf("%20s ", p.name);  //输出出队女士姓名
		DeQueue(Mdancers, p);   //男士出队
		printf("%20s\n", p.name); //输出出队男士姓名}
	if(!QueueEmpty(Fdancers)) 
	{
	//女士队列非空,输出队头女士的姓名
		p = GetHead(Fdancers); //取女士队头
		printf("The first woman to get a partner is:%s\n", p.name);
	}
	else if(!QueueEmpty(Mdancers)) 
	{//男士队列非空,输出队头男士的姓名
		p = GetHead(Mdancers); //取男士队头 
		printf("The first man to get a partner is:%s\n", p.name);
	}
	}
}

 

...全文
191 回复 打赏 收藏 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

50

社区成员

发帖
与我相关
我的任务
社区描述
产学研究,学术传承
社区管理员
  • 又菜又爱玩呜呜呜~
  • 两年半的个人练习生^_^
  • yolanda19910002
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧