> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/data-structures/circular-queue.md).

# 循环队列

### 为什么用循环队列

普通队列出队后前面的空间被浪费。循环队列用取模运算让队尾“绕回”开头，重复利用空间。

### 关键变量

* `front`：队头下标
* `rear`：队尾下标
* 容量 `MAXN`，判断队满需牺牲一个空间：`(rear + 1) % MAXN == front`

```cpp
const int MAXN = 10;
int q[MAXN];
int front = 0, rear = 0;

bool empty() { return front == rear; }
bool full()  { return (rear + 1) % MAXN == front; }

void push(int x) {           // 入队
    if (!full()) { q[rear] = x; rear = (rear + 1) % MAXN; }
}
int pop() {                  // 出队
    int x = q[front]; front = (front + 1) % MAXN; return x;
}
int frontVal() { return q[front]; }
```

### 与普通队列的区别

|      | 普通队列           | 循环队列                     |
| ---- | -------------- | ------------------------ |
| 空间利用 | 出队后前部浪费        | 循环利用                     |
| 判断队满 | `rear == MAXN` | `(rear+1)%MAXN == front` |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/data-structures/circular-queue.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
