zoukankan      html  css  js  c++  java
  • [leetCode]剑指 Offer 30. 包含min函数的栈

    解法

    这题的关键是设计一种数据结构,当栈中压入节点时可以同时记录当前栈的最小值

    class MinStack {
    
        class Node{
            int val;
            int min;
            Node next;
            public Node(int val, int min){
                this.val = val;
                this.min = min;
            }
        }
    
        private LinkedList<Node> stack;
    
        /** initialize your data structure here. */
        public MinStack() {
            stack = new LinkedList<>();
        }
        
        public void push(int x) {
            if(stack.isEmpty()){
                Node node = new Node(x,x);
                stack.push(node);
            }else{
                Node top = stack.peek();
                int min = Math.min(x,top.min);
                stack.push(new Node(x,min));
            }
        }
        
        public void pop() {
            stack.pop();
        }
        
        public int top() {
            return stack.peek().val;
        }
        
        public int min() {
            return stack.peek().min;
        }
    }
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(x);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.min();
     */
    

    自己实现栈

    class MinStack {
    
        class Node{
            int val;
            int min;
            Node next;
            public Node(int val, int min){
                this.val = val;
                this.min = min;
            }
        }
    
        private Node first;
    
        /** initialize your data structure here. */
        public MinStack() {
    
        }
        
        public void push(int x) {
            Node oldfirst = first;
            int min = x;
            if(oldfirst != null){
                min = Math.min(oldfirst.min,x);
            }
            first = new Node(x,min);
            first.next = oldfirst;
        }
        
        public void pop() {
            first = first.next;
        }
        
        public int top() {
           return first.val;
        }
        
        public int min() {
            return first.min;
        }
    }
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(x);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.min();
     */
    

    leetCode 主站同题

  • 相关阅读:
    (三)通用定时器的定时功能(不使用中断)
    (二)STM32中中断优先级理解
    (一)通用定时器的相关介绍
    Ambari client
    Ambari的资源池管理
    Sentry的授权模型
    关于yum
    Ambari-HDP
    Ambari的API调用
    CentOS上面搭建SVN服务器
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13859961.html
Copyright © 2011-2022 走看看