题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
import java.util.Stack;
public class Solution {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public Solution(){
stackData = new Stack<Integer>();
stackMin = new Stack<Integer>();
}
public void push(int node) {
if(stackMin.isEmpty()){
stackMin.push(node);
}else{
if(node <= this.min()){
stackMin.push(node);
}
}
stackData.push(node);
}
public void pop() {
if(stackData.isEmpty()){
// throws new RuntimeException("Your stack is empty");
}
int value = this.stackData.pop();
if(value == this.min()){
stackMin.pop();
}
}
public int top() {
if(stackMin.isEmpty()){
throw new RuntimeException("Your stack is empty.");
}
return stackMin.peek();
}
public int min() {
if(stackMin.isEmpty()){
throw new RuntimeException("Your stack is empty.");
}
return stackMin.peek();
}
}