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

时间:2015-01-18 05:17:10

标签: java stack

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

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?

的位置究竟会受到什么影响?

1 个答案:

答案 0 :(得分:3)

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

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

请参阅?当temp引用与head引用相同的Node时,将其前一个设置为null,然后将头设置为其前一个(您只需设置为null)。

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

  Node temp = head;
  head = head.previous;
  temp.previous = null;
相关问题