数据结构示例之圆形队列模拟舞会

来源:互联网 发布:windows多线程 编辑:程序博客网 时间:2024/05/13 22:00

以下为“使用圆形队列模拟舞会”的简单示例:

1. 用c语言实现的版本

#include<stdio.h>#include<stdlib.h>#include<string.h>#define MAX_DANCERS 100//最多跳舞人数#define QueueSize 100 //假定预分配的队列空间最多为100个元素  typedef struct {char name[20];char sex;  //性别,'F'表示女性,'M'表示男性} Person;typedef Person DataType;  //将队列中元素的数据类型改为Persontypedef struct{DataType data[QueueSize];int front;//头指针int rear;//尾指针}CirQueue;//初始化圆形队列void Initial(CirQueue *Q){Q->front = Q->rear = 0;}//判断队列是否为空int IsEmpty(CirQueue *Q){return Q->front == Q->rear;}//判断队列是否已满int IsFull(CirQueue *Q){return (Q->rear + 1) % QueueSize == Q->front;}//进入队列int EnQueue(CirQueue *Q, DataType *x){if (IsFull(Q)){printf("队列上溢"); //上溢,退出运行return -1;}memcpy(&(Q->data[Q->rear]), x, sizeof(DataType)); //新元素插入队尾Q->rear = (Q->rear + 1) % QueueSize; //循环意义下将尾指针加1return 1;}//弹出队列int DeQueue(CirQueue *Q, DataType *value){if (IsEmpty(Q)){printf("队列为空"); //下溢,退出运行return -1;}memcpy(value, &(Q->data[Q->front]), sizeof(DataType));Q->front = (Q->front + 1) % QueueSize;   //循环意义下的头指针加1return 1;}// 取队列顶元素int Front(CirQueue *Q, DataType* value){if (IsEmpty(Q)){printf("队列为空"); //下溢,退出运行return -1;}memcpy(value, &(Q->data[Q->front]), sizeof(DataType));return 1;}/* 获取队列长度 */int Length(CirQueue *Q){return (Q->rear - Q->front + QueueSize) % QueueSize;}//进行配对,结构数组dancer中存放跳舞的男女,num是跳舞的人数。void DancePartner(Person *dancer, int num){int i;Person p;CirQueue Mdancers, Fdancers;Initial(&Mdancers);//男士队列初始化Initial(&Fdancers);//女士队列初始化for (i = 0; i < num; ++i){//依次将跳舞者依其性别入队p = dancer[i];if (p.sex == 'F') //排入女队{EnQueue(&Fdancers, &p);   }else if ((p.sex == 'M')) //排入男队{EnQueue(&Mdancers, &p);}}printf("舞队是:\n");while (!IsEmpty(&Fdancers) && !IsEmpty(&Mdancers)){ //依次输入男女舞伴名DeQueue(&Fdancers, &p);     //女士出队printf("Female: %s ,", p.name);//打印出队女士名DeQueue(&Mdancers, &p);     //男士出队printf("Man: %s\n", p.name);    //打印出队男士名}//输出女士剩余人数及队头女士的名字if (!IsEmpty(&Fdancers)){ printf("还有 %d 个女士等下一轮.\n", Length(&Fdancers));Front(&Fdancers, &p);  //取队头printf("%s will be the first to get a partner. \n", p.name);}//输出男队剩余人数及队头者名字if (!IsEmpty(&Mdancers)){printf("还有%d 个男士等下一轮.\n", Length(&Mdancers));Front(&Mdancers, &p);printf("%s will be the first to get a partner.\n", p.name);}}//跳舞报名void InitialDancer(Person *dancer, int num){char UserName[32];char man = 'M';char female = 'F';for (int i = 0; i < num; ++i){sprintf(UserName, "name%d", i);strcpy(dancer[i].name, UserName);if (i%2 == 0){dancer[i].sex = man;}else{dancer[i].sex = female;}}}void main(){Person dancer[MAX_DANCERS];int n = 73;InitialDancer(dancer, n);//跳舞报名DancePartner(dancer, n); //进行配对}

运行结果如下图所示:


0 0