题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
import java.util.Stack;
import java.lang.Integer;
public class Solution {
public Stack<Integer> stack1 = new Stack<Integer>();
public Stack<Integer> stack2 = new Stack<Integer>();
public int min = Integer.MAX_VALUE;
public void push(int node) {
stack1.push(node);
if(min>node){
min = node;
}
stack2.push(min);
}
public void pop() {
if(!stack1.isEmpty()){
stack1.pop();
stack2.pop();
}
}
public int top() {
return stack1.peek();
}
public int min() {
if(!stack2.isEmpty()){
return stack2.peek();
}
return Integer.MAX_VALUE;
}
}