为什么将last.next分配给x,如果last将成为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++;
}
答案 0 :(得分:1)
语句last.next = x;
执行节点到链表末尾的实际添加。
(rest) -> (node) ===> (rest) -> (node) -> (x)
^ ^
| |
last last
但是,现在last
引用已过期;需要更新它以引用我们刚刚添加的最后一项,last = x;
。
(rest) -> (node) -> (x) ===> (rest) -> (node) -> (x)
^ ^
| |
last last