码迷,mamicode.com
首页 > 其他好文 > 详细

队列之银行排号模拟

时间:2014-12-09 15:46:05      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:c语言   cycqueue   typedef   sizeof   bankqueue   

//CycQueue.h

/*
Queue:First In First Out (FIFO)
避免假溢出:使用循环队列。
*/

#define QUEUEMAX 20

//1.定义队列结构
typedef struct 
{
	DATA data[QUEUEMAX];		//队列数组
	int head;					//队头
	int tail;					//队尾
}CycQueue;

//2.初始化队列
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);
}

//3.获取队列状态
int CycQueueIsEmpty(CycQueue *q)		//判断队列是否为空
{
	return (q->head==q->tail);
}

int CycQueueIsFull(CycQueue *q)			//判断队列是否已满
{
	return ((q->tail+1)%QUEUEMAX==q->head);
}

//4.入队操作
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;
	}
}

//5.出队操作
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]);
	}
}

//6.获取队列长度
int CycQueueLen(CycQueue *q)
{
	int n;
	n=q->tail-q->head;
	if(n<0)
		n=QUEUEMAX+n;

	return n;
}

//7.获取队列中第一个位置的数据
DATA *CycQueuePeek(CycQueue *q)
{
	if(q->head==q->tail)
	{
		printf("队列已经为空\n");
		return NULL;
	}
	else
	{
		return &(q->data[(q->head+1)%QUEUEMAX]);
	}
}

//BankQueue.c

//模拟银行顾客排号

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct 
{
	int num;		//顾客编号
	long time;		//进入队列时间

}DATA;

#include "CycQueue.h"
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 *queue;
	int select;
	num = 0;
	queue = CycQueueInit();
	do{
		printf("\n请选择具体操作:\n");
		printf("1.新到顾客\n");
		printf("2.下一个顾客\n");
		printf("0.退出\n");
		fflush(stdin);
		scanf("%d",&select);
		switch(select)
		{
			case 1:
				add(queue);
				printf("\n现在共有%d位顾客在等候!\n",CycQueueLen(queue));
				break;
			case 2:
				next(queue);
				printf("\n现在共有%d位顾客在等候!\n",CycQueueLen(queue));
				break;
			case 0:
				break;
		}
	}while(select!=0);

	CycQueueFree(queue);
	return 0;
}




队列之银行排号模拟

标签:c语言   cycqueue   typedef   sizeof   bankqueue   

原文地址:http://blog.csdn.net/huolang_vip/article/details/41823343

(0)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!