循环队列
队列的顺序存储结构
队头在下标为0 的位置,所以出队列的时间复杂度为O(n)
循环队列
容量是固定的,并且它的队头和队尾指针都可以随着元素入出队列而发生改变,这样循环队列逻辑上就好像是一个环形存储空间
让front 或 rear指针不断加1 ,即使超出了地址范围,也会自动从头开始。我们可以采取摸运算处理
(rear+1)%QueueSize
(front +1)%QueueSize
定义循环队列
#define MAXSIZE 100 typedef struct { ElemType *base; int front; int rear; }
初始化
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->font == q->rear) return ; *e = q->base[q->front]; q->front = (q->front+1)%MAXSIZE; }