【问题标题】:Stack implementation using LinkedList in Java在 Java 中使用 LinkedList 实现堆栈
【发布时间】:2021-10-22 03:08:54
【问题描述】:

我在 Leetcode 上发现了这个使用链表实现堆栈的解决方案,我理解了它背后的几乎所有逻辑,除了最小部分。谁能解释一下代码是如何在弹出第一个最小元素后继续跟踪最小元素的?

代码

class MinStack {
    private Node head;
        
    public void push(int x) {
        if (head == null) 
            head = new Node(x, x, null);
        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 val;
        int min;
        Node next;
            
        private Node(int val, int min, Node next) {
            this.val = val;
            this.min = min;
            this.next = next;
        }
    }
}

【问题讨论】:

  • 也许我误解了实现,但它似乎不起作用(Ideone demo)。
  • @Turing85 您使用的测试代码从推送0 开始并从那里递增,因此最小值始终为0
  • @TimMoore 我知道。但我通常希望数据结构在内部组织值(如最小堆)。但话又说回来:也许我误解了实施。如果没有明确的问题陈述,就很难知道数据结构的确切要求是什么。
  • 它不是按最小元素排序,它只是跟踪最小值。

标签: java linked-list stack


【解决方案1】:

当你将一个新节点压入栈顶时,新的最小值要么是新节点,要么是之前的最小值,存储在之前的头部。当您弹出磁头时,它会恢复到先前的最小值,存储在前一个磁头中。因为getMin() 总是查看当前头部,所以这给出了正确的结果。

尝试逐步浏览一些示例:

  1. 从空栈开始

  2. push 5 -> 与val = 5min = 5next = null 的一个节点堆叠

    (从现在开始,我将使用缩写符号(val, min, next),如(5, 5, null)

  3. push 10 -> 有两个节点的堆栈(10, 5, (5, 5, null))

  4. 推 1 -> (1, 1, (10, 5, (5, 5, null)))

  5. pop -> 回(10, 5, (5, 5, null))

  6. pop -> 回(5, 5, null)

【讨论】:

  • When you pop the head, it reverts back to the previous minimum, stored in the previous head. 这条线是金线,非常感谢。当我在 IDE 中调试代码时,我什至看到了这一点,但当时我并没有太在意,因为不知何故,我更加专注于内部正在发生的一些神奇的事情,我真的很想知道。但是现在当你提到它时,它立即点击了,现在一切都说得通了。再次感谢您!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 2021-10-30
  • 2021-06-06
  • 1970-01-01
  • 2019-11-11
  • 2020-10-24
  • 2015-11-15
相关资源
最近更新 更多