> 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/queue.md).

# 队列

### 队列的特点

**先进先出（FIFO）**：最先入队的元素最先出队。队尾入队，队头出队。

### 数组实现

```cpp
const int MAXN = 100;
int q[MAXN];
int front = 0, rear = 0;      // [front, rear) 区间存放元素

bool empty() { return front == rear; }
int  size()  { return rear - front; }

void push(int x) { q[rear++] = x; }     // 入队
void pop()       { if (!empty()) front++; }  // 出队
int  getFront()  { return q[front]; }   // 队头
```

> 原笔记的 `int q[5]` 长度写死、且被截断，容量应用常量。

### STL queue（推荐）

```cpp
#include <queue>
queue<int> q;
q.push(1);        // 入队
q.front();        // 队头
q.back();         // 队尾
q.pop();          // 出队（不返回值）
q.size();
q.empty();
```

### 普通队列的问题

出队只移动 `front`，前面的空间被浪费。反复使用时应改用**循环队列**（见《循环队列》）。

### 应用

* BFS 广度优先搜索
* 模拟排队、打印任务
* 滑动窗口 / 单调队列

### BFS 里的队列

```cpp
queue<int> q;
q.push(start);
vis[start] = true;
while (!q.empty()) {
    int u = q.front(); q.pop();
    for (int v : adj[u])
        if (!vis[v]) { vis[v] = true; q.push(v); }
}
```


---

# 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/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.
