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

package leetcode;

import java.util.Stack;

public class offer_30 {
    /** initialize your data structure here. */
    
    private Stack<Integer> s1;
    //辅助栈,存放当前最小元素
    private Stack<Integer> s2;
    public offer_30() {
        s1=new Stack<Integer>();
        s2=new Stack<Integer>();
    }
    
    public void push(int x) {
        s1.push(x);
        if(s2.isEmpty()) {s2.push(x);}
        else {
            //只有当x不大于当前栈中最小值时才存入s2中
            if(x<=s2.peek()) {s2.push(x);}
        }
    }
    
    public void pop() {
        if(s1.peek().equals(s2.peek())) {
            s2.pop();
        }
        s1.pop();
    }
    
    public int top() {
        return s1.peek();
    }
    
    public int min() {
        return s2.peek();
    }

}

 

posted on 2022-03-02 16:43  一仟零一夜丶  阅读(19)  评论(0)    收藏  举报