题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
解题思路
1.使用数据栈弹出到辅助栈,再从辅助栈弹回到数据栈,保存住数据栈的结构;
2.数据栈在不断弹出栈顶元素的过程中,通过一个变量保存住最小值。
代码
public class Solution {
Stack<Integer> data=new Stack<Integer>();
Stack<Integer> help=new Stack<Integer>();
public void push(int node) {
data.push(node);
}
public void pop() {
int p=data.pop();
}
public int top() {
return data.peek();
}
public int min() {
int min=Integer.MAX_VALUE;
while(data.isEmpty()!=true){
int node=data.pop();
if(node<min){
min=node;
}
help.push(node);
}
while(help.isEmpty()!=true){
data.push(help.pop());
}
return min;
}
}