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

posted @ 2019-09-15 16:23  schaffen  阅读(109)  评论(0编辑  收藏  举报