算法系列之-实现返回最小值的栈

import java.util.Stack;

/**
 * @类名称:Mystack -思路:
 *              使用两个栈,一个栈用来存放当前栈中
 *              的数据,功能类似正常的栈,StackData;第二个栈用于保存每一步的最小值。StackMin
 * @author 赵建银
 * @date 2017年12月26日
 * @time 下午12:49:42
 * @version 1.0
 */
public class Mystack {

    private Stack<Integer> stackData;// 存放当前数据
    private Stack<Integer> stackMin;// 存放最小值

    public Mystack() {
        this.stackData = new Stack<Integer>();
        this.stackMin = new Stack<Integer>();
    }

    /**
     * 
     * 将当前数据压入栈中,
     * 
     * @param newNum
     *            当前数据
     */
    public void push(int newNum) {
        if (this.stackMin.isEmpty()) {// 判断stackMin是否为空
            this.stackMin.push(newNum);// 压入
        } else if (newNum <= this.getMin()) {// 有数据,判断是否小于当前栈顶的值
            this.stackMin.push(newNum);// 小于压入
        }
        this.stackData.push(newNum);
    }

    /**
     * 数据出栈,与压入规则相同
     */
    public int pop() {
        if (this.stackData.isEmpty()) {
            throw new RuntimeException("stack is empty!");
        }
        int value = this.stackData.pop();
        if (value <= this.getMin()) {
            this.stackMin.pop();
        }
        return value;
    }

    public int getMin() {
        if (stackMin.isEmpty()) {
            throw new RuntimeException("stack is empty!");
        }
        return stackMin.peek();
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值