循环队列与顺序队列功能基本一致但就队的长度等方面略有不同,下面通过一个功能实现来体现它的基本操作
#define QueueMax 15
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("队列已满");
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("队列已空");
return NULL;
}
else
{
q->head = (q->head+1)%QueueMax;
return &(q->data[q->head]);//取出队头元素后,将队头指针加一
}
}
DATA *CycQueuePeek(CycQueue *q)
{
if(q->head ==q->tail)
{
printf("队列已空");
return NULL;
}
else
{
return &(q->data[(q->head+1)%QueueMax]);//取出队头元素后,将队头指针加一
}
}
int CycQueueLen(CycQueue *q)
{
return (q->tail-q->head);
}
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
typedef struct
{
int num;//顾客编号
long time;//进入队列时间
}DATA;
#include "CycQueue.c"
int num;//顾客编号
void add(CycQueue *q)
{
DATA data;
if(!CycQueueIsFull(q))
{
data.num ==++num;
data.time = time(NULL);
CycQueueIn(q,data);
}
else
printf("/n排队人太多,等待,,,,,");
}
void next(CycQueue *q)
{
DATA *data;
if(!CycQueueIsEmpty(q))
{
data = CycQueueOut(q);
printf("请编号为%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);
scanf("%d",&select);
switch(select)
{
case 1:
add(queue1);
printf("\n现在共有%d位客户在等待",CycQueueLen(queue1));
break;
case 2:
next(queue1);
printf("\n现在共有%d位客户在等待",CycQueueLen(queue1));
break;
case 0:
break;
}
}while(select!=0);
CycQueueFree(queue1);//释放
getch();
return 0;
}