题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
构造一个辅助栈来存储最小值,当数据栈添加数据时,辅助栈也同时添加当前的最小值。
import java.util.Stack;
public class Solution {
Stack<Integer> mStack=new Stack();
Stack<Integer> mMinNum=new Stack();
public void push(int node) {
mStack.push(node);
if(mMinNum.empty()||mMinNum.peek()>node){
mMinNum.push(node);
}else{
mMinNum.push(mMinNum.peek());
}
}
public void pop() {
mStack.pop();
mMinNum.pop();
}
public int top() {
return mStack.peek();
}
public int min() {
return mMinNum.peek();
}
}