题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
题目分析
使用一个辅助栈,每次主栈压入最小值时,将此最小值压入辅助栈即可
java代码
import java.util.Stack;
public class Solution {
Stack<Integer> S = new Stack<Integer>();
Stack<Integer> S_min = new Stack<Integer>();
public void push(int node) {
S.push(node);
if(S_min.empty()){
S_min.push(node);
}else{
if(node<=S_min.peek()){
S_min.push(node);
}
}
}
public void pop() {
int temp = S.peek();
S.pop();
if(temp == S_min.peek()){
S_min.pop();
}
}
public int top() {
return S.peek();
}
public int min() {
return S_min.peek();
}
}