题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
代码
import java.util.Stack;
public class Solution {
Stack<Integer> stack=new Stack<Integer>();
Stack<Integer> stack2=new Stack<Integer>();
public void push(int node) {
stack.push(node);
}
public void pop() {
stack.pop();
}
public int top() {
return stack.peek();
}
public int min() {
int m=Integer.MAX_VALUE;//一个最大值记住就是一个超级大的值
while(!stack.isEmpty()){
int node= stack.pop(); //出栈
if(node<m){
m=node;
}
stack2.push(node); //从stack出栈的数,进入stack2中
}
while(!stack2.isEmpty()){
stack.push(stack2.pop());//再把上面出栈的数进栈
}
return m;
}
}