关键点:
- 准备两个栈。一个数据栈stackData,一个存储当前栈中最小元素的栈stackMin。
- stackMin的栈顶元素永远是当前栈的最小元素
代码:
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 data) {
stackData.push(data);
if(stackMin.isEmpty()) {
stackMin.push(data);
}else {
if(data <= stackMin.peek()) {
stackMin.push(data);
}
}
}
public int pop() {
if(stackData.isEmpty()) {
throw new RuntimeException("Your stack is empty.");
}
int value = stackData.pop();
if(stackMin.peek() == value) {
stackMin.pop();
}
return value;
}
public int getMin() {
if(stackMin.isEmpty()) {
throw new RuntimeException("Your stack is empty.");
}
return stackMin.peek();
}
}
class MyStack2{
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public MyStack2() {
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}
public void push(int data) {
stackData.push(data);
if(stackMin.isEmpty()) {
stackMin.push(data);
}else if(data <= stackMin.peek()){
stackMin.push(data);
}else {
stackMin.push(stackMin.peek());
}
}
public int pop() {
if(stackData.isEmpty()) {
throw new RuntimeException("Your stack is empty");
}
stackMin.pop();
return stackData.pop();
}
public int getMin() {
if(stackMin.isEmpty()) {
throw new RuntimeException("Your stack is empty");
}
return stackMin.peek();
}
}