包含min函数的栈
描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
代码 (Java)
import java.util.Stack;
public class Solution {
Stack<Integer> stack = new Stack<>();
Stack<Integer> stackMin = new Stack<>();
public void push(int node) {
stack.push(node);
if (!stackMin.empty()) {
if (node < stackMin.peek())
stackMin.push(node);
else
stackMin.push(stackMin.peek());
} else {
stackMin.push(node);
}
}
public void pop() {
if (!stack.empty() && !stackMin.empty()) {
stack.pop();
stackMin.pop();
}
}
public int top() {
return stack.peek();
}
public int min() {
if (!stackMin.empty())
return stackMin.peek();
return 0;
}
}