# 数据结构 | 循环队列（基本操作及图示）

————————————————————————————————————————————

– – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – –

/* 定义链表队列 */

/* 初始化队列 */

/* 判断空或满 */

• 初始化时， front = rear = 0 时为空， Q->rear = 0+1 %100 = 1 ，队列未满可以插入队列

• 入队 3 个元素时， rear = 3 Q->rear = 3+1 %100 = 4 ，队列未满

• 入队 99 个元素时， rear = 99 Q->rear = 99+1 %100 = 0 ，队列满，不可入队

• 出队 2 个元素时， front = 2

出队后，执行两次 Q->front = (Q->front + 1) % MAXQSIZE，得到Q->front = 2

• 再次入队 1 个元素时， rear = 0 Q->rear = 99+1 %100=0 ，队列未满，可以入队

``` 1 #include <stdio.h>
2 #include <stdlib.h>
3 #define OK 1
4 #define ERROR 0
5 #define OVERFLOW -2
6 #define MAXQSIZE 100
7 typedef int Status;
8 typedef int QElemType;
9 typedef struct Node
10 {
11     QElemType *base; //初始化动态分配存储空间
12     int front;
13     int rear;
14 } SqQueue;
15 Status InitQueue(SqQueue *Q)
16 {
17     Q->base = (QElemType *)malloc(MAXQSIZE * sizeof(QElemType));
18     if (!Q->base)
19         exit(OVERFLOW);
20     Q->front = Q->rear = 0;
21     return OK;
22 }
23 Status EnQueue(SqQueue *Q, QElemType elem)
24 {
25     //队列为空时 1%100==1,队列满时(99+1)%100==0,最多容纳99个元素
26     if ((Q->rear + 1) % MAXQSIZE == (Q->front))
27         return ERROR;
28     Q->base[Q->rear] = elem;
29     Q->rear = (Q->rear + 1) % MAXQSIZE; //rear始终在0-100中循环
30     return OK;
31 }
32 Status OutQueue(SqQueue *Q, QElemType *e)
33 {
34     if (Q->front == Q->rear)
35         return ERROR;
36     *e = Q->base[Q->front];
37     Q->front = (Q->front + 1) % MAXQSIZE;
38     return OK;
39 }
40 Status PrintQueue(SqQueue Q)
41 {
42     printf("the queue is:");
43     for (int i = Q.front; i < Q.rear; ++i)
44         printf("%d ", Q.base[i]);
45     return OK;
46 }
47 int main()
48 {
49     SqQueue queue;
50     QElemType elem;
51     int i;
52     InitQueue(&queue);
53     printf("input:");
54     while(scanf("%d", &elem) != EOF)
55         EnQueue(&queue, elem);
56     PrintQueue(queue);
57     /* 输入要出队列的个数 */
58     printf("\noutput:");
59     scanf("%d", &i);
60     while(i != 0)
61     {
62         OutQueue(&queue, &elem);
63         i--;
64     }
65     PrintQueue(queue);
66     return OK;
67 }```
原文作者：hugh.dong
原文地址: https://www.cnblogs.com/hughdong/p/6841970.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。