20.包含min函数的栈

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

import java.util.Stack;

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() {
        Stack<Integer> temp = new Stack<Integer>();
        int min = Integer.MAX_VALUE;
        while(!stack.isEmpty()) {
            int top = stack.pop();;
            if(min > top) {
                min = top;
            }
            temp.push(top);
        }
        while(!temp.isEmpty()) {
            stack.push(temp.pop());
        }
        return min;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容