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