33 lines
778 B
Java
33 lines
778 B
Java
|
# 30. 包含 min 函数的栈
|
|||
|
|
|||
|
[NowCoder](https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49?tpId=13&tqId=11173&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
|||
|
|
|||
|
## 题目描述
|
|||
|
|
|||
|
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的 min 函数。
|
|||
|
|
|||
|
## 解题思路
|
|||
|
|
|||
|
```java
|
|||
|
private Stack<Integer> dataStack = new Stack<>();
|
|||
|
private Stack<Integer> minStack = new Stack<>();
|
|||
|
|
|||
|
public void push(int node) {
|
|||
|
dataStack.push(node);
|
|||
|
minStack.push(minStack.isEmpty() ? node : Math.min(minStack.peek(), node));
|
|||
|
}
|
|||
|
|
|||
|
public void pop() {
|
|||
|
dataStack.pop();
|
|||
|
minStack.pop();
|
|||
|
}
|
|||
|
|
|||
|
public int top() {
|
|||
|
return dataStack.peek();
|
|||
|
}
|
|||
|
|
|||
|
public int min() {
|
|||
|
return minStack.peek();
|
|||
|
}
|
|||
|
```
|