循环队列采用顺序存储结构,
简单的基本操作,入队,出队,取对头元素,判断是否空队列,队列长度
例代码:
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define ERROR 0
#define OK 1
#define OVERFLOW -1
#define MAXSIZE 10
typedef int Elemtype;
typedef int Status;
typedef struct SqQue
{
Elemtype *base;
int front;
int rear;
}SqQue;
Status InitQue(SqQue &q) //initialize the queue
{
q.base=(Elemtype*)malloc(MAXSIZE*sizeof(Elemtype));
if(!q.base) exit(OVERFLOW);
q.front=q.rear=0;
return OK;
}
bool EmptyQue(SqQue q) //if empty
{
if(q.front==q.rear) return true;
else return false;
}
Status EnQue(SqQue &q,Elemtype e)
{
if((q.rear+1)%MAXSIZE==q.front) return ERROR; //queue full
q.base[q.rear]=e;
q.rear=(q.rear+1)%MAXSIZE;
return OK;
}
Status DisplayQue(SqQue q)
{
int i;
if(EmptyQue(q)) printf("The queue is empty!\n");
else
{
i=q.front;
while(i!=q.rear)
{
printf("%d ",q.base[i]);
i=(i+1)%MAXSIZE;
}
printf("\n");
return OK;
}
}
int QueLength(SqQue q)
{
return (q.rear-q.front+MAXSIZE)%MAXSIZE;
}
Status DeQue(SqQue &q)
{
Elemtype e;
if(EmptyQue(q)) return ERROR;
e=q.base[q.front];
q.front=(q.front+1)%MAXSIZE;
return OK;
}
Status GetQueHead(SqQue q,Elemtype &e)
{
if(EmptyQue(q)) return ERROR; //queue empty
e=q.base[q.front];
return OK;
}
int main()
{
SqQue que;
int n,i,len;
Elemtype e;
InitQue(que);
if(EmptyQue(que)) printf("The initial queue is empty.\n");
printf("Input the number of queue n(don't greater than MAXSIZE):");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&e);
EnQue(que,e);
}
printf("After enqueue,the queue list:\n");
DisplayQue(que);
len=QueLength(que);
printf("The lenght of the queue is %d.\n",len);
GetQueHead(que,e);
printf("The head elem of the queue is %d.\n",e);
printf("Delete front elem\n");
DeQue(que);
printf("After delete front elem,the queue list:\n");
DisplayQue(que);
len=QueLength(que);
printf("The lenght of the queue is %d.\n",len);
GetQueHead(que,e);
printf("The head elem of the queue is %d.\n",e);
return 0;
}