题目入口:包含min函数的栈https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/使用两个栈,stack1为主栈,stack2为辅助栈,stack2是一个单调减的栈,栈顶为当前最小的数,向stack1加入元素的时候,需要判断要加入的元素是否为比stack2中最小的数还小,如果比stack2栈顶数还小的话,加入stack2成为栈顶,stack1弹出元素时,判断弹出的这个元素是否为stack2栈顶,如果是也需要把stack2的栈顶弹出,因为stack1中的数据才是真正的数据,stack1中不存在的数据,stack2中也不能存在.
class MinStack { private Stack<Integer> stack1 = null; private Stack<Integer> stack2 = null; public MinStack() { stack1 = new Stack<>(); stack2 = new Stack<>(); } public void push(int x) { stack1.push(x); if(stack2.empty() || stack2.peek() >= x){ stack2.push(x); } } public void pop() { if(stack1.peek().equals(stack2.peek())){ stack2.pop(); } stack1.pop(); } public int top() { return stack1.peek(); } public int min() { return stack2.peek(); } }