数据结构与算法基础 -- 最小栈

请实现一个基本栈 有一个getMin()函数 可以实现在O(1)时间内查询出栈内最小的值

  • 思路 用两个栈 一个就是存储数据 一个存储存储最小的值 这样需要getMin()的时候直接从辅助栈中pop()就好了
/**
 * 请实现一个基本栈  有一个getMin()函数 可以实现在O(1)时间内查询出栈内最小的值
 * @author zhx
 */
public class GetMinStack {

    public Stack<Integer> dataStack;
    public Stack<Integer> helpStack;

    public GetMinStack(){
        this.dataStack = new Stack<>();
        this.helpStack = new Stack<>();

    }

    public void push(Integer val){
        if (this.dataStack.isEmpty()){
            helpStack.push(val);
        }else if(this.helpStack.peek() <= val){
            this.helpStack.push(helpStack.peek());
        }else{
            this.helpStack.push(val);
        }
        this.dataStack.push(val);
    }

    public Integer pop(){
        if(dataStack.isEmpty()){
            throw new EmptyStackException();
        }
        this.helpStack.pop();
        Integer a = this.dataStack.pop();
        return a;
    }

    public Integer getMin(){
        if(helpStack.isEmpty()){
            throw new EmptyStackException();
        }
        return this.helpStack.peek();
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值