包含min函数的栈
包含min函数的栈
http://www.nowcoder.com/questionTerminal/4c776177d2c04c2494f2555c9fcc1e49
import java.util.Stack; public class Solution { Stack<Integer> stack = new Stack<Integer>(); int min; public void push(int node) { if(stack.isEmpty()) { min = node; stack.push(node); return; } if(node > min) { stack.push(node); return; } //当前插入的node是最小值时,将前一个最小值先一步再次压入栈,这样当最小值出栈时能立马知道下一个最小值是谁 stack.push(min); stack.push(node); min = node; } public void pop() { if(!stack.isEmpty() && stack.peek() == min) {//出栈的是最小值 //出栈时,先将最小值出栈。这时下一个node就是新的最小值 stack.pop(); min = stack.peek(); stack.pop(); return; } stack.pop(); } public int top() { return stack.peek(); } public int min() { return min; } }