简体   繁体   English

LinkedList 中除了头部或尾部以外的节点可以为空吗?

[英]Can nodes other than the head or the tail be null in a LinkedList?

My understanding is.我的理解是。

If the head is null, the list is empty.如果头为空,则列表为空。 If the tail is null, we have reached the end of the list.如果尾部为空,我们已经到达列表的末尾。

So, my question is, In a LinkedList abcd-null can either abc and d be null elements?所以,我的问题是,在 LinkedList abcd-null中,abc 和 d 可以是 null 元素吗?

Follow Up: In Java, is it mandatory for a Linked List to end in a null node?跟进:在Java中,链接列表是否必须以空节点结尾?

No, because if a node is null then it doesn't store information about the next node in the list.不,因为如果一个节点为null ,那么它不会存储有关列表中下一个节点的信息。 This means that there are no references to nodes past the null node, and in a language like Java (seen as though you tagged this post with the java tag) they'd be garbage collected.这意味着没有对null节点之后的节点的引用,并且在像 Java 这样的语言中(看起来好像你用java标签标记了这篇文章)它们将被垃圾收集。

Like others have mentioned, the answer is no.就像其他人提到的那样,答案是否定的。 And the answer to your follow-up question is yes.您的后续问题的答案是肯定的。 You can test this out yourself using the following code您可以使用以下代码自行测试

public static void main(String[] args){

LinkedList<String> ll=new LinkedList<>();
System.out.println(ll.peekFirst());}

The print message will be null, since the linkedlist has no elements, once you do start adding elements to the list, for lack of better words, it pushes the null reference towards the end.打印消息将为空,因为链表没有元素,一旦你开始向列表添加元素,由于缺少更好的词,它会将空引用推到最后。 Hence the end of the list always references to null.因此,列表的末尾总是引用 null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM