题目描述
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
实现
import java.util.Stack;
import java.util.Iterator;
public class Solution{
Stack<Integer> stack =new Stack<Integer>();
public void push(int node){
stack.push(node);
}
public void pop(){
stack.pop();
}
public void top(){
stack.peek();
}
public int min(){
int min=stack.peek();
int temp=0;
Iterator<Integer> iterator=stack.iterator();
while(iterator.hasNext()){
temp=iterator.next();
if(temp<min){
min=temp;
}
}
return min;
}
}
刚看题目的时候就是这个想法,不会实现,然后看了很多题解和思路,越看越迷,甚至怀疑题意,直到了解了iterator的解法,这样写思路很清晰也很简洁。别的解法甚至有重写了扩容的。。。给大佬跪了Orz,tql