'Why does insertion work in linked list when I put node!= null

I am trying to insert a node to the end of a linked list. I noticed that when I put node.next != null in the while loop it works but not when I put node!= null. Can you please tell me why is it like that?

This works

while(node.next!=null){
node = node.next;
    }
node.next = new Node(int 5);

This wont work.

while(node!=null){
        
  node = node.next;
    }
node = new Node(int 5);


Solution 1:[1]

Because when node.next is null it does not mean that it is pointing to some memory zone which has no object, but it means that is not pointing to anything.

So when you assign null to node you are not in some memory being pointed by someone, but you are literally nothing and nothing is pointing to you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Loris Securo