利用双栈实现min()
包含min函数的栈
http://www.nowcoder.com/questionTerminal/4c776177d2c04c2494f2555c9fcc1e49
代码思路很简单,就不叙述了,比较关键的地方是第10行必须是等号,否则连续输入两个相同最小值时,后面进行pop()操作时会存在bug,如果思考的不对,欢迎大家评论区指正
import java.util.Stack; public class Solution { Stack<Integer> stack = new Stack<Integer>(); Stack<Integer> stackMin = new Stack<Integer>(); public void push(int node) { stack.push(node); if (stackMin.empty()) { stackMin.push(node); }else if (stackMin.peek() >= node) { stackMin.push(node); } } public void pop() { if (stack.peek() == stackMin.peek()) { stackMin.pop(); } stack.pop(); } public int top() { return stack.peek(); } public int min() { return stackMin.peek(); } }