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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM