请大家澄清我的疑虑,这已经实现为链表。
当我们遍历一个链接列表时,我们正在写一个时间(temp!=null){}
中写入
所以请告诉我,这两种情况的区别是什么?
发布于 2022-07-31 12:03:50
通常,分别指向当前节点和下一个节点的指针。
发布于 2022-07-31 14:14:11
当您需要访问每个节点时,这个循环就是您所需要的:
while (temp!=null){
// Do the processing with this node
// ...
// Go to next
temp = temp.next;
}当您需要找出哪个是尾部节点时,情况就不同了。上面的循环将以temp为null结束,尽管循环确实访问了最后一个节点,但我们没有保留对它的引用。如果我们仍然想要这个引用,我们应该提前停止循环一个迭代。
这就是为什么我们需要一个不同的循环条件--当我们仍然有对最后一个节点的引用时,确保我们退出循环。
通常,在这样的循环之前,将单独检查temp是否为null:
if (temp == null) {
// deal with this boundary case
// ...
} else {
while (temp.next!=null){
// Usually there is no processing here. The purpose is only to find the tail
// Go to next
temp = temp.next;
}
// At this point temp is not null, but a reference to the tail node.
// Here can follow some logic that attaches a new node after that tail node
temp.next = new Node(newValue);
}https://stackoverflow.com/questions/73183074
复制相似问题