【题目】
实现一个栈,在基本功能基础上,能返回栈中最小元素
【要求】
各方法操作的时间复杂度为O(1)
可以使用现成的栈结构
【例子】
public class demo {
public static void main(String[] args) {
Mystack ms=new Mystack();
ms.push(3);
ms.push(4);
ms.push(5);
ms.push(1);
ms.push(2);
System.out.println(ms.getMin());//1
System.out.println(ms.pop());//2
System.out.println(ms.pop());//1
System.out.println(ms.pop());//5
System.out.println(ms.pop());//4
System.out.println(ms.pop());//3
System.out.println(ms.pop());//Your stack is empty
}
【代码】
import java.util.Stack;
public class Mystack {
private Stack<Integer> stackData;//私有成员变量,用来保存当前栈中的元素,正常栈
private Stack<Integer> stackMin;//用于保存每一步的最小值
public Mystack(){//构造方法
this.stackData=new Stack<Integer>();
this.stackMin=new Stack<Integer>();
}
public void push(int newNum){//入栈方法
if(this.stackMin.isEmpty()||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()){//若当前stackData弹出值是Min,则在stackMin栈中也弹出
this.stackMin.pop();
}
return value;
}
public int getMin(){//获得最小值
if(this.stackMin.isEmpty()){
throw new RuntimeException("Your stack is empty");
}
return this.stackMin.peek();
}
}