zoukankan      html  css  js  c++  java
  • 实现一个栈,在基本功能的基础上,可以返回栈中最小值


    import java.util.Stack;

    /**
    * 实现一个栈,在基本功能的基础上,可以返回栈中最小值
    */
    public class GetMinStack {

    public static class MyStack {

    public Stack<Integer> stackData;

    public Stack<Integer> stackMin;

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

    public void push(Integer value) {
    if (stackMin.isEmpty()) {
    stackMin.push(value);
    } else if (value <= getMin()) {
    stackMin.push(value);
    } else {
    stackMin.push(getMin());
    }
    stackData.push(value);
    }

    public Integer pop() {
    if (stackData.isEmpty()) {
    System.out.println("the stack is empty");
    return null;
    }
    stackMin.pop();
    return stackData.pop();
    }

    public Integer getMin() {
    if (stackMin.isEmpty()) {
    System.out.println("the stack is empty");
    return null;
    }
    return stackMin.peek();
    }

    }

    public static class MyStack2 {

    public Stack<Integer> stackData;

    public Stack<Integer> stackMin;

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

    public void push(Integer value) {
    if (stackMin.isEmpty()) {
    stackMin.push(value);
    } else if (value <= getMin()) {
    stackMin.push(value);
    }
    stackData.push(value);
    }

    public Integer pop() {
    if (stackData.isEmpty()) {
    System.out.println("the stack is empty");
    return null;
    }
    if (stackData.peek() == getMin()) {
    stackMin.pop();
    }
    return stackData.pop();
    }

    public Integer getMin() {
    if (stackMin.isEmpty()) {
    System.out.println("the stack is empty");
    return null;
    }
    return stackMin.peek();
    }

    }

    }

    /* 如有错误,欢迎批评指正 */
  • 相关阅读:
    case when in sql server's stored procedure
    Hadoop-2.2.0中国文献—— MapReduce 下一代 -- 公平调度
    cocos2d-x游戏循环和日程安排
    归并+高速分拣
    【Nginx】启动过程
    IOS线程操作(3)
    Android最方便的数据库--LitePal
    Android采用Application总结一下
    POJ 2151 Check the difficulty of problems (动态规划-可能DP)
    乞讨N!到底有多少0
  • 原文地址:https://www.cnblogs.com/laydown/p/12799227.html
Copyright © 2011-2022 走看看