155 最小栈

  1. class MinStack {
  2. private Deque<Integer> stack;
  3. private Deque<Integer> minStack;
  4. /** initialize your data structure here. */
  5. public MinStack() {
  6. stack = new LinkedList<Integer>();
  7. minStack = new LinkedList<Integer>();
  8. }
  9. public void push(int x) {
  10. stack.push(x);
  11. if (minStack.isEmpty() || x < minStack.peek())
  12. minStack.push(x);
  13. else
  14. minStack.push(minStack.peek());
  15. }
  16. public void pop() {
  17. minStack.pop();
  18. stack.pop();
  19. }
  20. public int top() {
  21. return stack.peek();
  22. }
  23. public int getMin() {
  24. return minStack.peek();
  25. }
  26. }
  27. /**
  28. * Your MinStack object will be instantiated and called as such:
  29. * MinStack obj = new MinStack();
  30. * obj.push(x);
  31. * obj.pop();
  32. * int param_3 = obj.top();
  33. * int param_4 = obj.getMin();
  34. */