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.stackMin.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();
}
不同点:peek 不改变栈的值(不删除栈顶的值),pop会把栈顶的值删除。
返回getMin栈的最小值