# 包含min函数的栈

![last modify](https://img.shields.io/static/v1?label=last%20modify\&message=2022-10-14%2014%3A59%3A33\&color=yellowgreen\&style=flat-square) [![](https://img.shields.io/static/v1?label=\&message=%E7%AE%80%E5%8D%95\&color=yellow\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/04/pages/R5NyOzkn3qAZy7wCx1pS#简单) [![](https://img.shields.io/static/v1?label=\&message=%E7%89%9B%E5%AE%A2\&color=green\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/04/pages/R5NyOzkn3qAZy7wCx1pS#牛客) [![](https://img.shields.io/static/v1?label=\&message=%E6%A0%88/%E9%98%9F%E5%88%97\&color=blue\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/04/pages/R5NyOzkn3qAZy7wCx1pS#栈队列)

> [包含min函数的栈\_牛客题霸\_牛客网](https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49)

**问题简述**

```
定义栈的数据结构，请在该类型中实现一个能够得到栈中所含最小元素的 min 函数，输入操作时保证 pop、top 和 min 函数操作时，栈中一定有元素。
```

**思路**

* 栈 `s` 正常模拟栈；
* 栈 `t` 保存所有**小于等于**栈顶的元素；
* 当 `s` 出栈元素等于 `t` 的栈顶元素时，`t` 也出栈；

<details>

<summary><strong>Python</strong></summary>

```python
class Solution:
    
    s = []
    t = []
    
    def push(self, node):
        self.s.append(node)
        if not self.t or self.t[-1] >= node:  # 注意是大于等于
            self.t.append(node)
        
    def pop(self):
        if self.s.pop() == self.t[-1]:
            self.t.pop()
        
    def top(self):
        return self.s[-1]
    
    def min(self):
        return self.t[-1]
```

</details>


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://imhuay.gitbook.io/studies/algorithms/problems/2022/04/niu-ke-0090-jian-dan-bao-han-min-han-shu-de-zhan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
