Cool Leetcode

1、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.

codes below

class MinStack {
private int size = 0;
private Node head = null;
class Node {
    int val;
    // every node contains min value at the moment it was pushed
    int min;
    Node next;
    Node(int v, int m) {val = v; min = m;}
}

public void push(int x) {
    int curMin = getMin();
    int newMin = x < curMin ? x : curMin;

    Node n = new Node(x, newMin);
    n.next = head;

    head = n;
    size++;
}

public void pop() {
    if (size <= 0)
        return;

    head = head.next;
    size--;
}

public int top() {
    if (size <= 0)
        return Integer.MAX_VALUE;

    return head.val;
}

public int getMin() {
    if (size <= 0)
        return Integer.MAX_VALUE;

    return head.min;
}}

这个使用ListNode的方法我还是没见过的。果然脑洞大开啊!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,774评论 0 33
  • 前言 由于现在 win10系统支持原生的linux 系统(如没有安装可以百度win10安装bash),所以,现在可...
    sT丶阅读 1,345评论 0 1
  • 世界若是须弥,我们便不过是寄身在这须弥间的一粒芥子。 长久以来,我们在这虚空一般的尘世间前行。即...
    辰丨熙阅读 211评论 1 3
  • 想为你洗衣服做余生所有的佳肴 早晨在玄关接吻傍晚并肩摄下夕阳 晚饭后赖在沙发上享受难得的休息时间 小猫在一旁的柜子...
    常樂丶阅读 266评论 0 0
  • 本篇文章已授权微信公众号 guolin_blog (郭霖)独家发布 前两天买了个Android手机(ps:之前一直...
    伪文艺大叔阅读 3,344评论 3 20