如果last会变成x,为什么last.next会被分配给x?我不明白将 x 分配给 last.next 有何影响。 这是队列的完整上下文:http://introcs.cs.princeton.edu/java/43stack/Queue.java.html
public void enqueue(Item item) {
Node x = new Node();
x.item = item;
if (isEmpty()) {
first = x;
last = x;
}
else {
last.next = x;
last = x;
}
N++;
}
最佳答案
语句last.next = x;
执行将节点实际添加到链表末尾的操作。
(rest) -> (node) ===> (rest) -> (node) -> (x)
^ ^
| |
last last
但是,现在 last
引用已经过时了;它需要更新以引用我们刚刚添加的最后一项,last = x;
就是这样做的。
(rest) -> (node) -> (x) ===> (rest) -> (node) -> (x)
^ ^
| |
last last
关于java - 了解普林斯顿队列教程中的 Enqueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33617569/