What is a Linked List ?
A linked list is formed by nodes that are linked together like a chain. Each node holds data, along with a pointer to the next node in the list.
The following image shows the basic structure of a Singly Linked List.
As you can see the Singly Linked List contains a head node: a pointer pointing to the first element of the list. Whenever we want to traverse the list, we can do so by using this head node.
Now using the below method of createLL(), you have created a linked list,
void createLL() {
head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
}
This can be represented using an image as below for easier understanding,
So in the createLL method you have now created a linked list like
10->20->30->40->null
here the first node which is also called as the "head node" contains the data 10.
Now inside the method printLL(), the first line is as below,
Node node = head;
Here you created a temporary node named "node" and assigned it to value of head. The head contains the information of the next node and the next node contains the information of its next node and so on. So now using your temporary node "node" and assigning it the value of headnode, you can traverse the whole linked list you created via the method createLL().
And in the while loop below,
while (node != null) {
System.out.println(node.data);
node = node.next;
}
You have now traversed the linked list one by one until it reached to null. Remember the last node of a linked list always points to null. This while loop did not reassign the value/data of any nodes. But it just iterated from the first node till it reached the lastnode using a temporary node called "node". And the while loop finally assigns the "node" variable to null.
So in the if loop comparison,
if (head.equals(node))
you are comparing,
if(10.equals(null)
which will return as false, since headnode still pointing to the 10 itself. only the temporary node "node" is pointing to the null which does not affect the headnode or any node of the linked list you have created.