定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数 (时间复杂度应为O(1))。

import java.util.Stack;
import java.util.Iterator;
public class Solution {

Stack<Integer> s = new Stack<Integer>();
public void push(int node) {
s.push(node);
}

public void pop() {
s.pop();
}

public int top() {
return s.peek();
}

public int min() {
int min = s.peek();
int temp = 0;
Iterator<Integer> it = s.iterator();
while(it.hasNext()){
temp = it.next();
if(min > temp){
min = temp;
}
}
return min; 
}
}

 

posted @ 2019-04-10 16:40  紫色的雪  阅读(633)  评论(0)    收藏  举报