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

  • 相关阅读:
    内置函数二
    通信的几个程序
    TCP协议和UDP协议
    异常处理
    logging模块
    网络编程一些概念
    hashlib
    序列化模块
    time,sys,os模块
    random模块
  • 原文地址:https://www.cnblogs.com/jose1125/p/5294972.html
Copyright © 2011-2022 走看看