美文网首页
剑指 Offer 30. 包含min函数的栈

剑指 Offer 30. 包含min函数的栈

作者: 上杉丶零 | 来源:发表于2021-08-12 16:09 被阅读0次
    class MinStack {
        private Stack<Integer> aStack;
        private Stack<Integer> bStack;
    
        public MinStack() {
            aStack = new Stack<>();
            bStack = new Stack<>();
        }
    
        public void push(int x) {
            aStack.push(x);
    
            if (bStack.empty() || bStack.peek() >= x) {
                bStack.push(x);
            }
        }
    
        public void pop() {
            if (aStack.pop().equals(bStack.peek())) {
                bStack.pop();
            }
        }
    
        public int top() {
            return aStack.peek();
        }
    
        public int min() {
            return bStack.peek();
        }
    }
    
    image.png

    相关文章

      网友评论

          本文标题:剑指 Offer 30. 包含min函数的栈

          本文链接:https://www.haomeiwen.com/subject/dpmlbltx.html