题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))
class MinStack {
Stack<Integer> A;
Stack<Integer> B;
/**
* initialize your data structure here.
*/
public MinStack() {
A = new Stack<>();
B = new Stack<>();
}
public void push(int x) {
A.add(x);
if (B.empty() || B.peek() >= x)
B.add(x);
}
public void pop() {
if (A.pop().equals(B.peek()))
B.pop();
}
public int top() {
return A.peek();
}
public int min() {
return B.peek();
}
}