数组实现循环队列
队列有两种形式:链式队列和静态队列,静态队列一般用数组实现,数组的优点是集中存储,内存访问快,若是用数组实现,一定是循环队列,否则会造成巨大的内存浪费。
应用场景:限流、排队
C语言:
// // Created by zhanghaodong on 2019-02-15. // /** * 循环队列 */ #include <stdio.h> #define MAXSIZE 10 #define OK 1 #define ERROR -1 typedef int Status; typedef int QElemType; typedef struct { QElemType data[MAXSIZE]; int front;/*头指针*/ int rear;/*尾指针,指向最后一个*/ int size; } SqQueue; Status initQueue(SqQueue *q) { q->front = 0; q->rear = 0; q->size = 0; return OK; } int queueLen(SqQueue *q) { return q->size; } Status enQueue(SqQueue *q, QElemType e) { /*队列满了*/ if (q->size == MAXSIZE) { return ERROR; } if (q->size > 0) { q->rear = (q->rear + 1) % MAXSIZE; } q->data[q->rear] = e; q->size++; return OK; } QElemType *deQueue(SqQueue *q) { /*队列空了*/ if (q->size == 0) { return ERROR; } QElemType *e = q->data[q->front]; q->front = (q->front + 1) % MAXSIZE; q->size--; return e; } void printStr(SqQueue *q) { if (q->rear > q->front) { for (int i = q->front; i <= q->rear; ++i) { printf("%d,", q->data[i]); } } else if (q->rear < q->front) { for (int i = q->front; i < MAXSIZE; ++i) { printf("%d,", q->data[i]); } for (int k = 0; k < q->rear; ++k) { printf("%d,", q->data[k]); } } else { printf("空队列"); } printf("\n"); } int main() { SqQueue *sq; initQueue(sq); for (int i = 0; i < 12; ++i) { QElemType k = i + 100; Status st = enQueue(sq, k); printf("%d插入结果:%d\n.", k, st); } printStr(sq); for (int j = 0; j < 6; ++j) { QElemType *e = deQueue(sq); printf("取出%d\n", e); } printStr(sq); for (int p = 0; p < 7; ++p) { QElemType k = p + 200; Status st = enQueue(sq, k); printf("%d插入结果:%d\n.", k, st); } printStr(sq); return 0; }
测试结果:
100插入结果:1 .101插入结果:1 .102插入结果:1 .103插入结果:1 .104插入结果:1 .105插入结果:1 .106插入结果:1 .107插入结果:1 .108插入结果:1 .109插入结果:1 .110插入结果:-1 .111插入结果:-1 .100,101,102,103,104,105,106,107,108,109, 取出100 取出101 取出102 取出103 取出104 取出105 106,107,108,109, 200插入结果:1 .201插入结果:1 .202插入结果:1 .203插入结果:1 .204插入结果:1 .205插入结果:1 .206插入结果:-1 .106,107,108,109,200,201,202,203,204,