java - 练习实现堆栈,需要帮助理解奇怪的行为

标签 java stack

我正在练习在 java 中为我的 compsci 类实现一个堆栈,这是我所拥有的:

public class Stack {
    private static Node head;

    private static class Node {
        private int value;
        private Node previous;

        Node(int i) {
        value = i;
        previous = null;
        }
    }

    public static void main(String[] args) {
        head = null;
        for (int i = 0; i < 10; i++) {
            Node n = new Node(i);
            n.previous = head;
            head = n;
        }
//        System.out.print(peek());
        System.out.print(pop().value);
        System.out.println();
        printValues(head);
    }

    private static void printValues(Node n) {
        while (n != null) {
            System.out.print(n.value + " ");
            n = n.previous;
        }
    }

    public static Node pop() {
        Node temp = head;
        temp.previous = null;
        head = head.previous;
//        temp.previous = null;
        return temp;
    }

    public static int peek() {
        return head.value;
    }
...
}

我的问题是 pop() 方法。按照目前的编写方式,当主程序运行时,只有 9 被打印到控制台,而 printValues 方法不会产生任何结果。但是如果我将 pop() 方法更改为:

    public static Node pop() {
        Node temp = head;
//        temp.previous = null;
        head = head.previous;
        temp.previous = null;
        return temp;
    }

现在主程序已完全正常工作,控制台打印 9、println(),然后打印 8 7 6 5 4 3 2 1 0。

temp.previous = null 的放置究竟会影响什么?

最佳答案

在第一个中,您将 head 变量设置为 null。

  Node temp = head;
  temp.previous = null;
  head = head.previous;

看到了吗?当 temp 引用与 head 引用相同的节点时,您将其前一个设置为 null,然后将 head 设置为其前一个(您刚刚设置为 null)。

在第二个中,您将 head 变量设置为前一个 head 的前一个,这是您的意图 - 然后然后将前一个 head 与其余的头部断开连接堆栈。

  Node temp = head;
  head = head.previous;
  temp.previous = null;

关于java - 练习实现堆栈,需要帮助理解奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28007382/

相关文章:

java - 交叉表报告 - 如何创建此类报告 jasper 或 crystal 报告

java - 堆栈、队列和链表脑筋急转弯的输出

flutter - Flutter:如何在带有动画的ListView中移动到最后一个位置

java - 路径行走/跟随不适用于所有情况

java - 如何在 Jetty 中使用 setThreadPool()

java - org.apache.catalina.LifecycleException : Failed to initialize component [Connector[HTTP/1. 1-8443]]

memory - 堆栈在 CPU 还是 RAM 中?

algorithm - 如果在 Breadth-FirstSearch(BFS) 算法中使用堆栈而不是 queueq 会发生什么?

c - 打印堆栈帧

java - Maven : how to create project with no propagating deps?