题目:包含min函数的栈
方法:双栈
stack2 与 stack1 同步进出栈,且栈顶始终记录 stack1 中的最小值
public class Solution {
private Deque<Integer> stack1 = new ArrayDeque<>();
private Deque<Integer> stack2 = new ArrayDeque<>();
public void push(int node) {
stack1.push(node);
if (stack2.isEmpty() || node <= stack2.peek()) {
stack2.push(node);
} else {
stack2.push(stack2.peek());
}
}
public void pop() {
stack1.pop();
stack2.pop();
}
public int top() {
return stack1.peek();
}
public int min() {
return stack2.peek();
}
}