实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。
【要求】 1.pop、push、getMin操作的时间复杂度都是O(1)。
2.设计的栈类型可以使用现成的栈结构
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){
//对于stackMin来说,首个数字放进,其余数字比较后放进
if (this.stackMin.isEmpty()){
this.stackMin.push(newNum);
}
else if (newNum <= this.getMin()){
this.stackMin.push(newNum);
}
//对于stackData来说,压入所有数字
this.stackData.push(newNuM);
}
//定义新栈的pop()方法
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();
}
}这段代码取自牛客网出的书的第一个,所以比较简单易懂。听说阅读和仿写代码对编程练习提升有所帮助,我打算把书中的有意思的代码都搬过来博客这里。若侵权,可通知我删除。


京公网安备 11010502036488号