获取栈中最小值的方法(创建两个栈来解决)
public class GetStackMin {
private Stack<Integer> dataStack;
private Stack<Integer> minStack;
public GetStackMin() {
this.dataStack = new Stack<Integer>();
this.minStack = new Stack<Integer>();
}
public void push(int num) {
if (minStack.isEmpty()) {
minStack.push(num);
} else if (num < minStack.peek()) {
minStack.push(num);
}else {
minStack.push(minStack.peek());
}
dataStack.push(num);
}
public int pop(){
if (dataStack.isEmpty()){
throw new RuntimeException("栈为空");
}
minStack.pop();
return dataStack.pop();
}
public int getMin(){
if (minStack.isEmpty()){
throw new RuntimeException("最小值栈为空");
}
return minStack.peek();
}
public static void main(String[] args) {
GetStackMin getStackMin = new GetStackMin();
getStackMin.push(5);
getStackMin.push(2);
getStackMin.push(5);
System.out.println(getStackMin.getMin());
}
}