题目

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。

代码

  1. import java.util.Stack;
  2. public class Solution {
  3. Stack<Integer> stackTotal = new Stack<Integer>();
  4. Stack<Integer> stackLittle = new Stack<Integer>();
  5. public void push(int node) {
  6. stackTotal.push(node);
  7. if(stackLittle.empty()){
  8. stackLittle.push(node);
  9. }else{
  10. if(node <= stackLittle.peek()){
  11. stackLittle.push(node);
  12. }else{
  13. stackLittle.push(stackLittle.peek());
  14. }
  15. }
  16. }
  17. public void pop() {
  18. stackTotal.pop();
  19. stackLittle.pop();
  20. }
  21. public int top() {
  22. return stackTotal.peek();
  23. }
  24. public int min() {
  25. return stackLittle.peek();
  26. }
  27. }