import java.util.Stack;
class newStack{
private Stack<Integer> s; // 普通的栈
private Stack<Integer> sMin; //负责弹出最小值的栈
public newStack() {
this.s = new Stack<Integer>();
this.sMin = new Stack<Integer>();
}
public void push(int value) {
s.push(value);
if (this.sMin.isEmpty()) {
this.sMin.push(value);
} else {
if (value < this.sMin.peek()) {
this.sMin.push(value);
}
}
}
public int pop() {
if (this.s.isEmpty()) {
throw new RuntimeException("Stack is empty");
}
int value = this.s.pop();
if (value == this.getMin()) {
this.sMin.pop();
}
return value;
}
public int getMin() {
if (this.sMin.isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return this.sMin.peek();
}
}
具有返回最小值功能的栈
最新推荐文章于 2024-01-20 14:59:43 发布