zoukankan      html  css  js  c++  java
  • 创建一个增加返回最小值功能的栈

    创建一个栈,增加返回最小值的功能

    需求:

    改造一个栈,在满足基本的条件下,再添加一个返回最小值的方法

    思路:

    建立两个栈,一个栈作为普通的数据(StackData)栈,另一个用来记录最小值(StackMin),当添加数据的时候,data栈直接增加数据,而StackMin栈则取出当前最小值与添加值相比较,如果添加值较小,则StackMin栈添加新值,否则再添加最小值.

    图示:

    代码:

    public class SpecialStack {
    
       
        public static class StackArray{
            private Stack<Integer> stackData;
            private Stack<Integer> stackMin;
    
            public StackArray() {
                this.stackData = new Stack<Integer>();
                this.stackMin  = new Stack<Integer>();
            }
    
            public void push(int newNum) {
                if (this.stackMin.isEmpty()){
                    this.stackMin.push(newNum);
                }else{
                    this.stackMin.push(newNum < this.stackMin.peek()?newNum:this.stackMin.peek());
                }
                this.stackData.push(newNum);
    
            }
    
            public int pop() {
                this.stackMin.pop();
                return this.stackData.pop();
            }
            public int getMin(){
                if (this.stackMin.isEmpty()){
                    throw new RuntimeException("Your Stack is Empty !");
                }
                return this.stackMin.peek();
            }
        }
        public static void main(String[] args) {
            StackArray stack = new StackArray();
            stack.push(3);
            System.out.println(stack.getMin());
            stack.push(5);
            System.out.println(stack.getMin());
            stack.push(2);
            System.out.println(stack.getMin());
            stack.push(4);
            System.out.println(stack.getMin());
            stack.push(1);
            System.out.println(stack.getMin());
    
        }
    }
    
  • 相关阅读:
    IOS UIwebview 背景色调整
    文件的创建 判断是否存在文件 读取 写入
    IOS 关于ipad iphone5s崩溃 解决
    iOS tabbar 控制器基本使用
    iOS 关于流媒体 的初级认识与使用
    总结 IOS 7 内存管理
    iOS 应用首次开启 出现引导页面
    IOS UItableView 滚动到底 触发事件
    IOS 应用中从竖屏模式强制转换为横屏模式
    iOS 定位系统 知识
  • 原文地址:https://www.cnblogs.com/Courage129/p/14165316.html
Copyright © 2011-2022 走看看