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