/*
循环队列 顺序存储结构
*/
#include <stdlib.h>
#include <stdio.h>
#define ERROR -1
#define OK 0
typedef int ElemType;
typedef struct RingQueue
{
ElemType *base;
int front;
int rear;
int rq_size;
}RingQueue;
int initRingQueue(RingQueue *rq,int rq_size)
{
rq->base = (ElemType *)malloc(rq_size * sizeof(ElemType));
if (!rq->base)
{
return ERROR;
}
rq->front = 0;
rq->rear = 0;
rq->rq_size = rq_size;
return OK;
}
int inRQueue(RingQueue *rq, ElemType data)
{
if ((rq->rear + 1) % rq->rq_size == rq->front)
{
return ERROR;
}
rq->base[rq->rear] = data;
rq->rear = (rq->rear + 1) % rq->rq_size;
return OK;
}
int outRQueue(RingQueue *rq, ElemType *data)
{
if (rq->front == rq->rear)
{
return ERROR;
}
*data = rq->base[rq->front];
rq->front = (rq->front + 1) % rq->rq_size;
return OK;
}
int main()
{
int rq_size = 10;
RingQueue *rq = (RingQueue *)malloc(sizeof(RingQueue));
initRingQueue(rq, rq_size);
for (int i=0;i<=10;i++)
{
int ret = inRQueue(rq, i);
printf("in i=%d ret=%d\n",i,ret);
}
for (int i =0;i<=10;i++)
{
int data = 0;
int ret = outRQueue(rq, &data);
printf("in i=%d ret=%d data=%d\n", i, ret,data);
}
return 0;
}
rear指向的是下一次可以存放值的地方。。。。。
当一直inRQueue不out时 rear指针指向最后一个节点位置,再inRQueue 时 就认为队满了 其实这个时候最后一个节点还没有存放数据