循环队列
循环队列的容量是固定的,并且它的队头和队尾指针都可以随着元素出入队列而发生改变,这样循环队列逻辑上就好像是一个环形的存储空间。注意rear指针指向的是下一个要插入的位置(注意是空的)。
我们发现循环队列只需要灵活改变front和rear指针就可以了。也就是让他两不断加1,即使超出了地址范围,也可以自动从头开始,可以采取取模运算处理:
- (rear+1)%QueuSize
- (front+1)%QueuSize
定义一个循环队列
#define MAXSIZE 100
typedef struct
{
ElemType *base;//用于存放内存分配基地址,也可以用数组
int front;
int rear;
}*cycleQueue;
初始化一个循环队列
initQueue(cycleQueue *q)
{
q->base = (ElemType *)malloc(MAXSIZE*sizeof(ElemType));
if (!q->base)
exit(0);
q->front = q->next = 0;
}
入队列操作
InsertQueue(cycleQueue *q, ElemType e)
{
if((q->rear + 1)%MAXSIZE == q->front)
return;
q->base[q->rear] = e;
q->rear = (q->rear+1)%MAXSIZE ;
}
出队列操作
DeleteQueue(cycleQueue *q,ElemType *e)
{
if(q->front == q->rear)
return;//队列为空
*e = q->base[q->front];
q->front = (q->front+1)%MAXSIZE;
}