剑指Offer23-包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的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 int top() {
   
        return 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;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-03 18:13
点赞 评论 收藏
分享
06-07 19:59
门头沟学院 C++
补药卡我啊😭:都快15年前的了还在11新特性
你的简历改到第几版了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务