20_____包含main函数的栈

题目描述:

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

import java.util.Stack;
import java.util.Iterator;

public class Solution {

    Stack<Integer> s=new Stack<>();
    public void push(int node) {
        s.push(node);
    }
    
    public void pop() {
        s.pop();
    }
    
    public int top() {
        return s.peek();
    }
    
    public int min() {
        
        Iterator <Integer> it=s.iterator();
        int min=top();   //不能用  s.top
        while(it.hasNext()){
            int temp=it.next();   //注意不能直接用 it.next()进行比较
            if(temp<min){
                min=temp;
            }
        }
        
        return min;
    }
}

 

posted @ 2019-09-04 20:08  德鲁大叔817  阅读(151)  评论(0编辑  收藏  举报