java.util.Stack類中的peek()方法

  java.util.stack類中經常使用的幾個方法:isEmpty(),add(),remove(),contains()等各類方法都不難,但須要注意的是peek()這個方法。java

  peek()查看棧頂的對象而不移除它。this

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("=============");
    }
}

  運行結果:3spa

       3code

         1對象

       1blog

       3rem

相關文章
相關標籤/搜索