我正在练习在 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/