首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >temp.next和temp有什么区别?

temp.next和temp有什么区别?
EN

Stack Overflow用户
提问于 2022-07-31 11:52:13
回答 2查看 29关注 0票数 1

请大家澄清我的疑虑,这已经实现为链表。

当我们遍历一个链接列表时,我们正在写一个时间(temp!=null){}

  • When,我们在后面插入元素,然后在When (temp.next!=null){}

中写入

所以请告诉我,这两种情况的区别是什么?

EN

回答 2

Stack Overflow用户

发布于 2022-07-31 12:03:50

通常,分别指向当前节点和下一个节点的指针。

票数 0
EN

Stack Overflow用户

发布于 2022-07-31 14:14:11

当您需要访问每个节点时,这个循环就是您所需要的:

代码语言:javascript
复制
while (temp!=null){
    // Do the processing with this node
    // ...
    // Go to next
    temp = temp.next;
}

当您需要找出哪个是尾部节点时,情况就不同了。上面的循环将以tempnull结束,尽管循环确实访问了最后一个节点,但我们没有保留对它的引用。如果我们仍然想要这个引用,我们应该提前停止循环一个迭代。

这就是为什么我们需要一个不同的循环条件--当我们仍然有对最后一个节点的引用时,确保我们退出循环。

通常,在这样的循环之前,将单独检查temp是否为null:

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73183074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档