zoukankan      html  css  js  c++  java
  • LC 155 Min Stack

    问题描述

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

    • push(x) -- Push element x onto stack.
    • pop() -- Removes the element on top of the stack.
    • top() -- Get the top element.
    • getMin() -- Retrieve the minimum element in the stack

    参考答案

    class MinStack {
        
        private Node head;
        /** initialize your data structure here. */
        public MinStack() {
            
        }
        
        public void push(int x) {
            if(head == null){
                head = new Node(x,x);
            }else{
                head = new Node(x,Math.min(x,head.min),head);
            }
        }
        
        public void pop() {
            head = head.next;
        }
        
        public int top() {
            return head.val;
        }
        
        public int getMin() {
            return head.min;
        }
        
        private class Node{
            int min;
            int val;
            Node next;
            private Node(int val, int min){
                this(val,min,null);
            }
            private Node(int val, int min, Node next){
                this.val = val;
                this.min = min;
                this.next = next;
            }
        }
    }

    附加注释

    Node

    新建一个 Node,包含 val、min 和 next(下一个节点)。val 记录当前值,min是最小值,next是下一个节点。

    push 函数

    进入push函数,判断 Node head 的属性。

    如果是初始化 Node,那么 val 和 min 都是 输入值 x。

    如果不是初始化 Node,那么建立一个新的 head,val 为输入值x,min值 是 当前值和上一个head节点的min值,即min值将会从同一直继承下去, next 指向上一个head。Node 一直会在整个链条上更新。

    pop函数

    当前 head节点 往回退,最后的节点被剔除了。

  • 相关阅读:
    C++内存检测函数_CrtSetBreakAlloc()
    Detours 的配置
    浅析杀毒软件开发原理
    Sqlite3初学
    java拦截器、过滤器的区别
    sudo 设置无需密码
    Visual Studio 2012/2010/2008 远程调试
    jquery 随笔
    网页中显示xml,直接显示xml格式的文件
    centos7.2_x64安装mysql.tar.gz
  • 原文地址:https://www.cnblogs.com/kykai/p/11523264.html
Copyright © 2011-2022 走看看