定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
import java.util.Stack;
public class Solution {
Stack<Integer> stack = new Stack<Integer>();
//弄一个最小值栈 即可
Stack<Integer> minStack = new Stack<Integer>();
public void push(int node) {
stack.push(node);
//更新 min栈
if(minStack.isEmpty() || minStack.peek() >= node) {
minStack.push(node);
}
}
public void pop() {
if(minStack.peek() == stack.peek()) {
minStack.pop();
}
stack.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return minStack.peek();
}
}