栈--提供获取最小元素方法的栈

import java.util.NoSuchElementException;
import java.util.Stack;

/**
 * 一个提供获取最小元素方法的栈。
 *
 * 说明:
 *  1)每次向操作栈中添加元素后,在辅助栈中也添加一个元素 且 向辅助栈中添加的元素是当前操作栈中的最小元素。
 *  2)每次弹出操作栈的栈顶元素后,将辅助栈的栈顶元素也弹出。
 *  3)无论是向操作栈中push元素还是pop元素,辅助栈都会随之做相同的动作,故辅助栈的栈顶元素始终等于当前操作栈的最小元素。
 *
 */
public class CustomStack {


    // 操作栈,提供push、pop功能
    private Stack<Integer> originStack = new Stack<Integer>();

    // 辅助栈,提供min功能
    private Stack<Integer> minStack = new Stack<Integer>();


    /**
     * 同时向操作栈和辅助栈中添加元素:将新元素添加到操作栈中,然后将操作栈中的最小元素添加到辅助栈中。
     *
     * @param num
     * @return
     */
    public Integer push(Integer num) {
        Integer result = originStack.push(num);

        if (minStack.isEmpty() || num < minStack.peek()) {
            minStack.push(num);
        } else {
            minStack.push(minStack.peek());
        }

        return result;
    }

    /**
     * 同时将操作栈和辅助栈的栈顶元素弹出
     *
     * @return
     */
    public Integer pop() {
        Integer top = originStack.pop();
        minStack.pop();
        return top;
    }

    /**
     * 获取栈中最小的元素
     *
     * @return
     */
    public Integer min() {
        if (!originStack.isEmpty() && !minStack.isEmpty()) {
            return minStack.peek();
        } else {
            throw new NoSuchElementException();
        }
    }


    public static void main(String[] args) {

        CustomStack customStack = new CustomStack();
        customStack.push(2);
        customStack.push(3);
        customStack.push(4);
        customStack.push(5);
        System.out.println(customStack.min());
        customStack.pop();
        customStack.push(1);
        System.out.println(customStack.min());
        customStack.pop();
        System.out.println(customStack.min());

    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值