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节点 往回退,最后的节点被剔除了。

  • 相关阅读:
    pointer-like classes, 关于智能指针
    non-explicite-one-argumen-constructor
    车道标线分割与分类
    matlab变量更新
    matlab求余
    MATLAB中图像的读取与显示
    提取文件一部分内容
    NetCore3.1 使用 mongoDb 存储日志,提升查询效率
    C#代码实现阿里云消息服务MNS消息监听
    盘点这些年我出的书,以及由此得到的收获
  • 原文地址:https://www.cnblogs.com/kykai/p/11523264.html
Copyright © 2011-2022 走看看