定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
代码
static class MinStack {
private Stack<Integer> stack = new Stack<>();
private Stack<Integer> min = new Stack<>();
public void push(Integer val) {
if (val == null) {
return;
}
stack.push(val);
if (min.isEmpty()) {
// 如果当前栈中没有数据,则第一个数据一定是最小的,直接放入min中
min.push(val);
} else {
// 如果当前栈中没有数据,则把栈min中当前栈顶的值和当期的值较小的那个放到栈顶
// 都次都将最小的放到栈顶,是为了保证pop出stack中的值时,min中依旧是最小的,直到stack中与min中对应的值被pop
min.push(min.peek() > val ? val : min.peek());
}
}
public Integer peek() {
return stack.peek();
}
public Integer pop() {
// 栈min和stack的深度是一样的
// 所以需要对stack做pop的时候,min也要pop
min.pop();
return stack.pop();
}
public Integer getMin() {
return min.peek();
}
public boolean isEmpty() {
return stack.isEmpty();
}
}
public static void main(String[] args) {
MinStack stack = new MinStack();
stack.push(5);
stack.push(7);
stack.push(6);
stack.push(3);
stack.push(9);
stack.push(2);
// 结果是
// 2 2 2是最小,pop出2后,此时最小值是3
// 3 9 pop出9.但是3依然是最小值,且3还在stack中未被pop
// 3 3 pop出3,此时最小值时5
// 5 6
// 5 7
// 5 5
// 这里解释了为什么每次都要把当前最小值push到min栈中,保证min最小值对应的stack中的值未被pop出前,
// 每次pop其他值,获取最小值都是真确的
while (!stack.isEmpty()) {
System.out.println(stack.getMin() + " " + stack.pop());
}
}