定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))
import java.util.Stack;
public class Solution {
private Stack<Integer> stack = new Stack<Integer>();
private Stack<Integer> minStack=new Stack<Integer>();
//每次放一个数的时候都要判断最小栈中的数
public void push(int node) {
stack.push(node);
if (minStack.isEmpty()) {
minStack.push(node);
} else {
if (node <= minStack.peek()) {
minStack.push(node);
}
}
}
public void pop() {
if (stack.isEmpty()) {
return;
} else {
if (stack.pop() == minStack.peek()) {
minStack.pop();
}
}
}
public int top() {
return stack.peek();
}
public int min() {
return minStack.peek();
}
}