题目是这样的,要求实现一个带有min函数的栈
下面是我的代码
public class Solution {
Stack<Integer> stack = new Stack<>();
Stack<Integer> minStack = new Stack<>();
public void push(int node) {
stack.push(node);
if (minStack.isEmpty()){
minStack.push(node);
}
if (!minStack.isEmpty() && minStack.peek() > node){
minStack.push(node);
}
}
public void pop() {
if (stack.isEmpty() && minStack.isEmpty()){
return;
}
stack.pop();
if (stack.peek().equals(minStack.peek())){
minStack.remove(stack.peek());
}
}
public int top() {
return stack.peek();
}
public int min() {
return minStack.peek();
}
public static void main(String[] args) {
Solution solution = new Solution();
solution.push(3);
System.out.println(solution.min());
solution.push(4);
System.out.println(solution.min());
solution.push(2);
System.out.println(solution.min());
solution.push(3);
System.out.println(solution.min());
solution.pop();
System.out.println(solution.min());
solution.pop();
System.out.println(solution.min());
solution.pop();
System.out.println(solution.min()); //这行会遇到遇到问题
solution.push(0);
System.out.println(solution.min());
}
}
在提交时会遇到这个问题
如果把代码中出问题的行注释掉就会的到正确的结果,也就是在当minStack为空时就什么都不返回,可是什么都不返回应该怎么写啊。min()方法总是要返回一个值,抛出异常提交也不能通过,
这下应该怎么改啊