155. 最小栈 + 栈的使用

155. 最小栈

LeetCode_155

题目描述

相似题目

剑指 Offer 30. 包含min函数的栈
面试题59 - II. 队列的最大值
155. 最小栈

代码实现

class MinStack {

    /** initialize your data structure here. */
    Stack<Integer> minSta;
    Stack<Integer> sta;
    public MinStack() {
        minSta = new Stack<>();
        sta = new Stack<>();
    }
    
    public void push(int x) {
        if(minSta.isEmpty() || minSta.peek() >= x){
            minSta.push(x);
        }
        sta.push(x);
    }
    
    public void pop() {
        if(sta.peek() <= minSta.peek()){
            minSta.pop();
        }
        sta.pop();
    }
    
    public int top() {
        return sta.peek();
    }
    
    public int getMin() {
        return minSta.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */
posted @ 2021-03-19 21:45  Garrett_Wale  阅读(22)  评论(0编辑  收藏  举报