155. 最小栈

package leetcode;

import java.util.Stack;

public class demo_155 {
    private Stack<Integer> s1;
    private Stack<Integer> s2;

    /** initialize your data structure here. */
    public demo_155() {
        s1=new Stack<Integer>();
        s2=new Stack<Integer>();
    }
    
    public void push(int val) {
        s1.push(val);
        if(s2.isEmpty()) {s2.push(val);}
        else {
            //只有当x小于当前栈中最小值时才存入s2中
            if(val<=s2.peek()) {s2.push(val);}
        }
    }
    
    public void pop() {
        if(s1.peek().equals(s2.peek())) {
            s2.pop();
        }
        s1.pop();
    }
    
    public int top() {
        return s1.peek();
    }
    
    public int getMin() {
        return s2.peek();
    }
}

 

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