实现一个特殊的栈,在栈的基本功能的基础上,增加一个功能:返回栈中最小元素 要求:
public static class MyStack1 {
private Stack<Integer> dataStack;
private Stack<Integer> minStack;
public MyStack1() {
this.dataStack = new Stack<>();
this.minStack = new Stack<>();
}
public int getMin() {
if(minStack.isEmpty()) {
throw new RuntimeException("Your stack is empty!");
}
return minStack.peek();
}
public void push(int element) {
if(minStack.isEmpty()) {
minStack.push(element);
} else if(element <= getMin()) {
minStack.push(element);
} else {
int min = minStack.peek();
minStack.push(min);
}
dataStack.push(element);
}
public int pop() {
if(dataStack.isEmpty()) {
throw new RuntimeException("Your stack is empty!");
}
minStack.pop();
return dataStack.pop();
}
}
思路2对思路1进行了空间上的优化,在思路1中可能会压入重复的元素,优化思路如下:
public static class MyStack2 {
private Stack<Integer> dataStack;
private Stack<Integer> minStack;
public MyStack2() {
this.dataStack = new Stack<>();
this.minStack = new Stack<>();
}
public int getMin() {
if(minStack.isEmpty()) {
throw new RuntimeException("Your stack is empty!");
}
return minStack.peek();
}
public void push(int element) {
if(minStack.isEmpty()) {
minStack.push(element);
} else if(element <= getMin()) {
minStack.push(element);
} // 只有当push的元素小于minStack的栈顶元素时才minStack才push
dataStack.push(element);
}
public int pop() {
if(dataStack.isEmpty()) {
throw new RuntimeException("Your stack is empty!");
}
int value = dataStack.pop();
// 只有dataStack的栈顶元素=minStack的栈顶元素时,minStack才弹出
if(value == getMin()) {
minStack.pop();
}
return value;
}
}