数据结构-课程设计-模拟舞伴配对
程序员文章站
2024-03-02 12:44:10
...
Queue.h
class Queue {
public:
char *base;
int head;
int end;
void InitQueue();
void EnQueue(char e);
char DeQueue();
void DestoryQueue();
};
Queue.cpp
#include "Queue.h"
#include <cstdlib>
#define Maxsize 1000
using namespace std;
//构造空队列
void Queue::InitQueue() {
base = (char *)malloc(Maxsize * sizeof(char));
if(!base) exit (-2);
head = end = 0;
return ;
}
//插入元素e为Q的队尾元素
void Queue::EnQueue(char e) {
if((end + 1) % Maxsize == head) exit (-1); //存储分配失败
base[end] = e;
end = (end + 1) % Maxsize;
return ;
}
//若队列不空 删除队头元素 并用e返回其值
char Queue::DeQueue() {
char e;
if(head == end) exit (-1);
e = base[head];
head = (head + 1) % Maxsize;
return e;
}
//销毁
void Queue::DestoryQueue() {
free(base);
return ;
}
main.cpp
#include <iostream>
#include <cstdio>
#include "Queue.h"
using namespace std;
int main() {
Queue M, F;
int nM, nF;
char c;
cout << "输入男队人数:";
cin >> nM;
cout << "输入女队人数:";
cin >> nF;
M.InitQueue();
F.InitQueue();
cout << "男队舞者:" << endl;
for(int i = 1; i <= nM; ++i) {
cin >> c;
getchar();
M.EnQueue(c);
}
cout << "女队舞者:" << endl;
for(int i = 1; i <= nF; ++i) {
cin >> c;
getchar();
F.EnQueue(c);
}
int n; //轮数
cout << "输入配对轮数:";
cin >> n;
for (int i = 1; i <= n; i++) {
cout << "第" << i << "轮配对:" << endl;
for (int j = 1; j <= (nM > nF ? nF : nM); j++) {
char s = M.DeQueue(), z = F.DeQueue();
cout << s << ' ' << z << endl;
M.EnQueue(s);
F.EnQueue(z);
}
}
M.DestoryQueue();
F.DestoryQueue();
return 0;
}
运行结果
上一篇: 学习CSS的10大理由
推荐阅读