设计一个有getMin功能的栈 pop、push、getMin操
作者:
敲一手烂代码 | 来源:发表于
2016-09-23 12:02 被阅读57次class MYStack {
private Stack<Integer> stackData;
private Stack<Integer> minStack;
public MYStack() {
this.stackData = new Stack<Integer>();
this.minStack = new Stack<Integer>();
}
public int getMin() {
if (this.minStack.isEmpty()) {
throw new RuntimeException("栈为空");
} else {
return this.minStack.peek();
}
}
public void push(int num) {
this.stackData.push(num);
if (this.minStack.isEmpty()) {
this.minStack.push(num);
} else if (num <= this.minStack.peek()) {
this.minStack.push(num);
}
}
public int pop() {
if (stackData.isEmpty()) {
throw new RuntimeException("栈为空");
} else {
int val = stackData.pop();
if (val == minStack.peek()) {
minStack.pop();
}
return val;
}
}
}
本文标题:设计一个有getMin功能的栈 pop、push、getMin操
本文链接:https://www.haomeiwen.com/subject/ihetyttx.html
网友评论