循环队列
#pragma warning(disable:4996)
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define QUEUEMAX 15
typedef struct {
int num;
long time;
}DATA;
typedef struct {
DATA data[QUEUEMAX];
int head;
int tail;
}CycQueue;
//循环队列
CycQueue *CycQueueInit() {
CycQueue *q;
if (q = (CycQueue *)malloc(sizeof(CycQueue))) {
q->head = 0;
q->tail = 0;
return q;
}
else {
return NULL;
}
}
void CycQueueFree(CycQueue *q) {
if (q != NULL) {
free(q);
}
}
int CycQueueIsEmpty(CycQueue *q) {
return (q->head == q->tail);
}
int CycQueueIsFull(CycQueue *q) {
return ((q->tail + 1) % QUEUEMAX == q->head);
}
int CycQueueIn(CycQueue *q, DATA data) {
if ((q->tail + 1) % QUEUEMAX == q->head) {
printf("队列已经满了!\n");
return 0;
}
else {
q->tail = (q->tail + 1) % QUEUEMAX;
q->data[q->tail] = data;
return 1;
}
}
DATA *CycQueueOut(CycQueue *q) {
if (q->head == q->tail) {
printf("队列已经空了!\n");
return NULL;
}
else {
q->head = (q->head + 1) % QUEUEMAX;
return &(q->data[q->head]);
}
}
int CycQueueLen(CycQueue *q) {
int n;
n = q->tail - q->head;
if (n < 0) {
n = QUEUEMAX + n;
}
return n;
}
DATA *CycQueuePeek(CycQueue *q) {
if (q->head == q->tail) {
printf("队列已经空了!\n");
return NULL;
}
else {
return &(q->data[(q->head + 1) % QUEUEMAX]);
}
}
int num;//顾客序号
void add(CycQueue *q) {
DATA data;
if (!CycQueueIsFull(q)) {
data.num = ++num;
data.time = time(NULL);
CycQueueIn(q, data);
}
else {
printf("\n排队的人太多,请稍后再排队!\n");
}
}
void next(CycQueue *q) {
DATA *data;
if (!CycQueueIsEmpty(q)) {
data = CycQueueOut(q);
printf("\n请编号为%d的顾客办理业务!\n", data->num);
}
if (!CycQueueIsEmpty(q)) {
data = CycQueuePeek(q);
printf("请编号为%d的顾客准备,马上将为您办理业务!\n", data->num);
}
}
int main() {
CycQueue *queue1;
int i, n;
char select;
num = 0;
queue1 = CycQueueInit();
if (queue1 == NULL) {
printf("创建队列时出错!\n");
getch();
return 0;
}
do {
printf("\n请选择具体操作:\n");
printf("1.新到顾客\n");
printf("2.下一个顾客\n");
printf("0.退出\n");
fflush(stdin);
select = getch();
switch (select) {
case '1':
add(queue1);
printf("\n现在一共有%d位顾客在等候!\n", CycQueueLen(queue1));
break;
case '2':
next(queue1);
printf("\n现在共有%d为顾客在等候!\n", CycQueueLen(queue1));
break;
case '0':
break;
}
} while (select != '0');
CycQueueFree(queue1);
getch();
return 0;
}