简体   繁体   中英

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?

Follow Up: In Java, is it mandatory for a Linked List to end in a null node?

No, because if a node is null then it doesn't store information about the next node in the list. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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