带最小值操作的栈

来源:互联网 发布:淘宝图片数据包 编辑:程序博客网 时间:2024/05/19 13:09

实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值。

你实现的栈将支持pushpop 和 min 操作,所有操作要求都在O(1)时间内完成。

public class Solution {    private Stack<Integer> stack;    private Stack<Integer> minStack;        public Solution() {        // do initialize if necessary        stack = new Stack<Integer>();        minStack = new Stack<Integer>();    }    public void push(int number) {        // write your code here        if(stack.isEmpty() || number < minStack.peek()){            stack.push(number);            minStack.push(number);        }else{            stack.push(number);            minStack.push(minStack.peek());        }    }    public int pop() {        // write your code here        minStack.pop();        return stack.pop();    }    public int min() {        // write your code here        return minStack.peek();    }}

0 0
原创粉丝点击