#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef struct QNode{
int data;
struct QNode *next;
}QNode,*QueuePtr;
struct LinkQueue{
QueuePtr front;
QueuePtr rear;
};
LinkQueue Q;
int deletedCount = 0;
void menu();
void QueueUp();
void Treatment();
void Display();
void Count();
Status QueueEmpty(LinkQueue);
//初始化队列
Status InitQueue(LinkQueue &Q){
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if(!Q.front) exit(OVERFLOW);
Q.front -> next = NULL;
return OK;
}
//在队尾插入新元素
Status EnQueue(LinkQueue &Q,int e){
QueuePtr p;
p = (QueuePtr)malloc(sizeof(QNode));
if(!p) exit(OVERFLOW);
p -> data = e;
p -> next = NULL;
Q.rear -> next = p;
Q.rear = p;
return OK;
}
//删除对头元素
Status DeQueue(LinkQueue &Q,int &e){
QNode *p;
if(QueueEmpty(Q)) return ERROR;
p = Q.front -> next;
e = p -> data;
Q.front -> next = p -> next;
if(Q.rear == p)
Q.rear = Q.front;
free(p);
deletedCount++;
return OK;
}
//求队列中元素的个数
int QueueLength(LinkQueue Q){
QueuePtr p;
int length = 0;
if(Q.front == NULL) exit(ERROR);
p = Q.front;
while(p != Q.rear){
length++;
p = p -> next;
}
return length;
}
//检查是否为空队列
Status QueueEmpty(LinkQueue Q){
return Q.front == Q.rear;
}
//排队
void QueueUp(){
int newNum,count;
//printf("QueueUp");
//InitQueue(Q);
printf("\n\n\n\t\t请输入序号:");
scanf ("%d",&newNum);
EnQueue(Q,newNum);
count = QueueLength(Q);
//成功插入元素后,显示排在前面总共有多少人
printf("\n\n\n\t\t您排在队伍里第 %d 位\n\t\t前面还有 %d 位顾客.",count,count - 1);
printf("\n\n\t\t请按任意键返回主菜单\n\n\n");
system("pause");
getchar();
system("CLS");
menu();
}
//支付
void Treatment(){
int e;
//printf("Treatment");
if(!QueueEmpty(Q)){
DeQueue(Q,e);
printf("\n\n\n\t请序号为 %d 的顾客支付.",e);
}
else
printf("\n\n\t\t当前没有顾客在排队!");
printf("\n\n\t请按任意键返回主菜单\n\n\n");
system("pause");
getchar();
system("CLS");
menu();
}
//查看排队
void Display(){
QueuePtr p;
//printf("Display");
if(!QueueEmpty(Q)){
//输出所有已排队的
printf("\n\n\n\t从对首到队尾所有排队人的序号为:");
p = Q.front -> next;
while(p != NULL){
printf("\n\t%d",p -> data);
p = p -> next;
}
}
else
printf("\n\n\t\t当前没有人在排队!");
printf("\n\n\t请按任意键返回主菜单\n\n\n");
system("pause");
getchar();
system("CLS");
menu();
}
//统计已支付和未支付人数
void Count(){
//printf("Count");
printf("\n\n\n\t\t已支付人数:%d",deletedCount);
printf("\n\t\t未支付人数:%d",QueueLength(Q));
printf("\n\n\t\t请按任意键返回主菜单\n\n\n");
system("pause");
getchar();
system("CLS");
menu();
}
void menu(){
int select;
printf("\n\n\t\t 杂货店排队模拟程序");
printf("\n\n\t\t\t1.排队.");
printf("\n\t\t\t2.支付.");
printf("\n\t\t\t3.查看排队.");
printf("\n\t\t\t4.统计并查看已支付和未支付人数.");
printf("\n\t\t\t5.退出.");
printf("\n\n\t\t请输入数字选择相应操作:");
do{
scanf("%d",&select);
switch(select){
case 1:
system("CLS");
QueueUp();
break;
case 2:
system("CLS");
Treatment();
break;
case 3:
system("CLS");
Display();
break;
case 4:
system("CLS");
Count();
break;
case 5:
system("CLS");
break;
default:
printf("\n\t\t错误!请重新输入数字选择相应操作:");
}
}while(!(select > 0 && select <= 5));
}
int main(){
InitQueue(Q);
menu();
return 0;
}
|