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

时间:2023-12-05 11:51:32

  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