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

# 栈

### 栈的特点

**后进先出（LIFO）**：最后入栈的元素最先出栈。只能在栈顶操作。

### 数组实现

下标从 0 开始，`top` 指向栈顶元素，空栈时 `top = -1`：

```cpp
const int MAXN = 100;
int a[MAXN];
int top = -1;                 // 空栈

bool empty() { return top == -1; }
bool full()  { return top == MAXN - 1; }

void push(int x) { if (!full()) a[++top] = x; }   // 入栈
void pop()       { if (!empty()) top--; }         // 出栈
int  getTop()    { return a[top]; }               // 栈顶
```

> 原笔记用 `if (top < 芜湖)` 是不可运行的占位写法，容量要用常量。

### STL stack（推荐）

```cpp
#include <stack>
stack<int> st;
st.push(1);        // 入栈
st.top();          // 栈顶
st.pop();          // 出栈（不返回值）
st.size();         // 元素个数
st.empty();        // 是否为空
```

### 应用

* 括号匹配
* 表达式求值 / 中缀转后缀
* 函数的递归调用（系统栈）
* 单调栈（求下一个更大元素）

### 括号匹配示例

```cpp
bool check(string s) {
    stack<char> st;
    for (char c : s) {
        if (c == '(') st.push(c);
        else if (c == ')') {
            if (st.empty()) return false;
            st.pop();
        }
    }
    return st.empty();
}
```


---

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