如何在链表中选择合适的if语句?

How to choose proper if statements in linked list?

这些 if 语句有什么区别?

  1. if (current.next!=null)

  2. if (current!=null)

我假设您正在迭代列表并且您想知道您何时位于链接列表的末尾。 如果您有以下情况:

if (current.next!=null){
    current = next
}

那就没关系了。他们都很好。考虑到 current 永远不会是 null.

考虑以下链表:

HEAD ---> ["value2" | -]--> ["value3" | -]--> ["last_value" | null]

假设 current 指向 "value3":

HEAD ---> ["value2" | -]--> ["value3" | -]--> ["last_value" | null]
                                 ↑

那么current.next != null就是true,因为current.next实际上是"next"节点。

现在假设 current 移动到 "last_value",现在我们将有:

HEAD ---> ["value2" | -]--> ["value3" | -]--> ["last_value" | null]
                                                    ↑

现在 current != nulltruecurrent.nextnull(这表明没有更多节点)。

所以 "Choosing proper" if 语句不是一个好问题,因为它实际上取决于您要检查的内容,它们是两种不同的验证。