顺序实现循环队列
代码如下:
#include<stdio.h>
#include<malloc.h>
#define MAXSIZE 100
struct Queue{
int *base;
int front;
int rear;
};
struct Queue InitQueue();
int QueueLength(struct Queue *Q);
void EnQueue(struct Queue *Q,int e);
int DeQueue(struct Queue *Q);
int main()
{
struct Queue Q;
Q=InitQueue();
int i,j;
for (i=0;i<10;i++)
{
EnQueue(&Q,i);
}
for (j=0;j<10;j++)
{
printf("%d ",DeQueue(&Q));
}
return 0;
}
struct Queue InitQueue()
{
struct Queue Q;
Q.base=(int *)malloc(MAXSIZE*sizeof(int ));
if (!Q.base)
exit(0);
Q.front=Q.rear=0;
return Q;
}
int QueueLength(struct Queue *Q)
{
return (Q->rear-Q->front+MAXSIZE)%MAXSIZE;
}
void EnQueue(struct Queue *Q,int e)
{
if ((Q->rear+1)%MAXSIZE==Q->front)
exit(0);
Q->base[Q->rear]=e;
Q->rear=(Q->rear+1)%MAXSIZE;
}
int DeQueue(struct Queue *Q)
{
int e;
if (Q->front==Q->rear)
exit(0);
e=Q->base[Q->front];
Q->front=(Q->front+1)%MAXSIZE;
return e;
}
|