包含min函数的栈 java

版权声明:博客内容为本人自己所写,请勿转载。 https://blog.csdn.net/weixin_42805929/article/details/83059665

包含min函数的栈 java

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

代码:

import java.util.*;

public class Solution {
    Stack<Integer> stack = new Stack<>();
    public void push(int node) {
        stack.push(node);
    }
    
    public void pop() {
        stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int min() {
        int temp = 0;
        int min = stack.peek();
        Iterator<Integer> it = stack.iterator();
        while(it.hasNext()){
            temp = it.next();
            if(min > temp){
                min = temp;
            }
        }
        return min;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42805929/article/details/83059665