• 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

  • 相关阅读:
    Ubuntu 装JDK
    U盘文件夹被病毒隐藏,且不能取消解决办法
    wireshark: there are no interfaces on which a capture can be done
    [转]Ubuntu 常用快捷键10个
    恢复被win7覆盖的Ubuntu Grub
    U盘安装Win7 64位
    荣耀3X畅玩版狙击红米note!
    Secret and Whisper
    360 chrome不能登录Google账户
    周鸿祎仍想做手机
  • 原文地址:https://www.cnblogs.com/jose1125/p/5294972.html
Copyright © 2020-2023  润新知