题目描述
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
实现 MinStack 类:
MinStack()初始化堆栈对象。void push(int val)将元素val推入堆栈。void pop()删除堆栈顶部的元素。int top()获取堆栈顶部的元素。int getMin()获取堆栈中的最小元素。

题目思路:
java
class MinStack {
private Stack<Integer> stack;
private Stack<Integer> min_stack;
public MinStack() {
stack = new Stack();
min_stack = new Stack();
}
public void push(int val) {
stack.push(val);
if(min_stack.isEmpty() || val <= min_stack.peek()){
min_stack.push(val);
}
}
public void pop() {
if(stack.pop().equals(min_stack.peek())){
min_stack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min_stack.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
利用两个栈实现,一个是正常存储数据,一个存储当前的栈中的最小值,每次push都需要更新。