155. 最小栈
作者:
上杉丶零 | 来源:发表于
2019-02-18 17:09 被阅读0次class MinStack {
private Stack<Integer> stackData = new Stack<Integer>();
private Stack<Integer> stackMin = new Stack<Integer>();
public void push(int x) {
stackData.push(x);
if (stackMin.isEmpty() || x < stackMin.peek()) {
stackMin.push(x);
} else {
stackMin.push(stackMin.peek());
}
}
public void pop() {
if (stackMin.isEmpty()) {
throw new RuntimeException("栈为空");
}
stackMin.pop();
stackData.pop();
}
public int top() {
if (stackMin.isEmpty()) {
throw new RuntimeException("栈为空");
}
return stackData.peek();
}
public int getMin() {
if (stackMin.isEmpty()) {
throw new RuntimeException("栈为空");
}
return stackMin.peek();
}
}

image.png
本文标题:155. 最小栈
本文链接:https://www.haomeiwen.com/subject/szqzeqtx.html
网友评论