实现了min方法的栈

package com.banban.CeShi;

import java.util.Stack;

/**
 * 定义一个实现了min方法的栈,min方法返回当前栈最小元素。要求min,push,pop时间复杂度O(1)		
 * 		方法一:
 * 			双栈实现:minstack栈存储最小值
 *
 */

public class MinStack {
    private  Stack<Integer> DataStack =  new Stack<>();
    private  Stack<Integer> MinStack = new Stack<>();
    public void push(Integer x){
        if (DataStack.isEmpty()&&MinStack.isEmpty()){
            DataStack.push(x);
            MinStack.push(x);
        }else {
            if (x <= MinStack.peek()){
                DataStack.push(x);
                MinStack.push(x);
            }else {
                DataStack.push(x);
            }
        }
    }
    public Integer pop(){
        if (DataStack.peek().equals(MinStack.peek())){
            MinStack.pop();
            return DataStack.pop();
        }else {
            return DataStack.pop();
        }
    }
    public Integer min(){
        return  MinStack.pop();
    }

}

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页