题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
使用最小值辅助栈.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| Stack<Integer> stack = new Stack();
Stack<Integer> minStack = new Stack();
public void push(int node) { stack.push(node); if (minStack.isEmpty() || minStack.peek() > node) { minStack.push(node); } else { minStack.push(minStack.peek()); } }
public void pop() { minStack.pop(); stack.pop(); }
public int top() { return stack.peek(); }
public int min() { return minStack.peek(); }
|