
自定义栈 O(1)时间内返回最小值?
public class MinStack {
Stack<Integer> dataStack = new Stack<>();
Stack<Integer> assistStack = new Stack<>();
public void push(int node) {
dataStack.push(node);
if(assistStack.isEmpty() || node < assistStack.peek()){
assistStack.push(node);
}else {
assistStack.push(assistStack.peek());//保证此位置出栈后能正确返回最小值
}
}
public void pop() {
if(!dataStack.isEmpty() && !assistStack.isEmpty()){
dataStack.pop();
assistStack.pop();
}
}
public int top() {
if(dataStack.isEmpty())
throw new RuntimeException("error: stack is empty");
return dataStack.peek();
}
public int min() {
if(assistStack.isEmpty()){
throw new RuntimeException("error: stack is empty");
}
return assistStack.peek();
}
}




近期评论