题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
代码示例
import java.util.Stack;
public class Offer21 {
public static void main(String[] args) {
Offer21 stack = new Offer21();
stack.push(1);
stack.push(2);
stack.push(0);
System.out.println(stack.min());
stack.pop();
System.out.println(stack.min());
stack.pop();
System.out.println(stack.min());
}
private Stack<Integer> dataStack = new Stack<>();
private Stack<Integer> minStack = new Stack();
public void push(int val) {
dataStack.push(val);
if (minStack.isEmpty()) {
minStack.push(val);
} else {
minStack.push(Math.min(minStack.peek(), val));
}
}
public void pop() {
dataStack.pop();
minStack.pop();
}
public int top() {
return dataStack.peek();
}
public int min() {
return minStack.peek();
}
}