zoukankan      html  css  js  c++  java
  • java.util.Stack类中的peek()方法

      java.util.stack类中常用的几个方法:isEmpty(),add(),remove(),contains()等各种方法都不难,但需要注意的是peek()这个方法。

      peek()查看栈顶的对象而不移除它。

    import java.util.Stack;
    
    
    public class MyStack1 {
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;
        
        public MyStack1(){
            this.stackData = new Stack<Integer>();
            this.stackMin = new Stack<Integer>();
        }
        public void push(int newNum){
            if (this.stackData.isEmpty()){
                    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 ("Your stack is empty");
            }
            int value  = this.stackData.pop();
                if(value == this.getmin()){
                    this.stackMin.pop();
                }
            return value;
        }
        public int getmin(){
            if (this.stackMin.isEmpty()){
                    throw new RuntimeException("Your stack is empty");
            }
            return this.stackMin.peek();
        }
        public static void main(String[] args) {
            MyStack1 stack1 = new MyStack1();
            stack1.push(3);
            System.out.println(stack1.getmin());
            stack1.push(4);
            System.out.println(stack1.getmin());
            stack1.push(1);
            System.out.println(stack1.getmin());
            System.out.println(stack1.pop());
            System.out.println(stack1.getmin());
    
            System.out.println("=============");
        }
    }

      运行结果:3

           3

             1

           1

           3

  • 相关阅读:
    Twitter注册
    iOS项目的完整重命名方法图文教程
    加载gif动态图的三种方式
    只 一行显示可左右滚动的文本(UITextField中文限制)
    iOS学习资料链接
    GCD常用方法
    移动端轮播完整版css3加原生写法
    zepto-touch.js插件
    移动端续讲及zepto移动端插件外加touch插件介绍
    解决ios和Android的差异
  • 原文地址:https://www.cnblogs.com/jose1125/p/5294972.html
Copyright © 2011-2022 走看看