栈后进先出....对栈的操作仅限于push和pop,我们不妨再加一个stack min_stack来维护栈的最小值列表(按照最小值更新的顺序,注意这里一定也要添加等于最小值的输入)
class MinStack {
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> min_stack = new Stack<Integer>();
public void push(int x) {
if(min_stack.isEmpty()||x<=min_stack.peek())
{
min_stack.push(x);
}
stack.push(x);
}
public void pop() {
if(!min_stack.isEmpty()&&stack.peek().equals(min_stack.peek()))
{
min_stack.pop();
}
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return min_stack.peek();
}
}