一:要求:
病人到医院排队看病,在排队过程中,主要重复以下两件事情:
-
病人到达诊室,将病历本交给护士,在等待队列中候诊。
-
护士从等待队列中取出下一位病人的病历,该病人进入诊室就诊。
要求编程模拟这个过程。
二:代码
cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
typedef int QElemType;
typedef struct QNode
{
QElemType data;
struct QNode* next;
}QNode, * QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
void init(LinkQueue& q)
{
q.front = new QNode;
q.front->next = nullptr;
q.rear = q.front;
}
void push(LinkQueue& q, QElemType x)
{
QueuePtr p = new QNode;
p->data = x;
p->next = nullptr;
q.rear->next = p;
q.rear = p;
}
void pop(LinkQueue& q, QElemType& e)
{
e = 0;
QueuePtr p;
if (q.rear == q.front) {
cout << "已空" << endl; return;
}
p = q.front->next;
e = p->data;
q.front->next = p->next;
if (p == q.rear)
q.rear = q.front;
delete p;
}
bool empty(LinkQueue& q)
{
return q.front == q.rear;
}
QElemType gettop(LinkQueue& q)
{
if (empty(q)) {
cout << "已空" << endl; return -1;
}
else return q.front->next->data;
}
void clear(LinkQueue& q)
{
while (q.front->next)
{
QueuePtr p = q.front->next;
q.front->next = p->next;
delete p;
}
q.rear = q.front;
}
void destroy(LinkQueue& q)
{
while (q.front)
{
q.rear = q.front->next;
delete q.front;
q.front = q.rear;
}
}
void display(LinkQueue& q)
{ if(empty(q)) { cout << "已空" << endl; return; }
QueuePtr p= q.front->next;
while (p)
{
cout << p->data; cout << " ";
p = p->next;
}
}
int check(LinkQueue& q, int id)
{
if (empty(q)) { return 0; }
QueuePtr p = q.front->next;
while (p)
{
if (p->data == id) return 1;
p = p->next;
}
return 0;
}
void see()
{
LinkQueue q;
init(q);
int n; int flag = 1;
while (flag) {
cout << "1:排队 2:就诊 3:查看排队 4:下班 请选择:";
cin >> n;
switch (n)
{
case 1:
cout << "请输入病历号";
int id;
cin >> id;
if (check(q, id) == 1) {
cout << "病历号重复,请重新输入";
cin >> id;
}
push(q, id);
break;
case 2: int e;
pop(q, e);
if (e == 0) cout << "没有排队的病人" << endl;
else cout << e << "病人请就诊"<<endl; break;
case 3:
cout << "排队的病人"; display(q); cout << endl; break;
case 4:
cout << "请以下排队的病人下午就诊:"; display(q); flag = 0; cout << endl;
cout << "下班";
break;
default:break;
}
}
}
int main()
{
see();
return 0;
}
这里就一个see()函数和check()是特意实现的,其他都是队列正常操作。