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

  • 相关阅读:
    PAT(B) 1037 在霍格沃茨找零钱(Java)
    PAT(B) 1043 输出PATest(Java)统计
    PAT(B) 1063 计算谱半径(Java)
    绘制虚线
    contentMode
    数字签名是什么
    动态设置 button的 name 的话 闪动的问题 解决
    setValuesForKeysWithDictionary 的用法
    获得 当前时间
    iOS 键盘类型
  • 原文地址:https://www.cnblogs.com/kykai/p/11523264.html
Copyright © 2011-2022 走看看