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的方法我還是沒見過的。果然腦洞大開??!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,890評論 0 33
  • 前言 由于現(xiàn)在 win10系統(tǒng)支持原生的linux 系統(tǒng)(如沒有安裝可以百度win10安裝bash),所以,現(xiàn)在可...
    sT丶閱讀 1,389評論 0 1
  • 世界若是須彌,我們便不過是寄身在這須彌間的一粒芥子。 長久以來,我們在這虛空一般的塵世間前行。即...
    辰丨熙閱讀 224評論 1 3
  • 想為你洗衣服做余生所有的佳肴 早晨在玄關(guān)接吻傍晚并肩攝下夕陽 晚飯后賴在沙發(fā)上享受難得的休息時間 小貓?jiān)谝慌缘墓褡?..
    常樂丶閱讀 288評論 0 0
  • 本篇文章已授權(quán)微信公眾號 guolin_blog (郭霖)獨(dú)家發(fā)布 前兩天買了個Android手機(jī)(ps:之前一直...
    偽文藝大叔閱讀 3,406評論 3 20

友情鏈接更多精彩內(nèi)容