educative.io

Educative

The Head Node - a Node itself or a Pointer to the first Node?

The example Link List in this section uses a Node as a Head pointer. This data value in this node is ignored (it stays zero - the initialized value - through all insertions). It I snot clear why one should use a Node as a pointer instead of pointing to the Node itself? If one points to the first Node as Head, it saves space (one less Node object) and is also more intuitive? Under this mechanism, the logic for insertingAtHead would run as follows:
Node new_node = new Node();
new_node.data = 2; //sample made up value
new_node.next = headNode;
headNode = new_node;

I have tried this and it works fine. Could someone share what is the typical LinkedList HeadNode implementation in Java? Should one use a Node just for pointer purpose or is it okay to label the leading Node as Head?

@CodeRank You are right, we can use the head node to store data and save memory. This approach would be slightly efficient in terms of space, hence, it should be preferred, in my opinion. However, the code for insert, delete, update and read would be different when the head node is initially null.
The code you provided for insert at head seems to be correct, however, it ignores the case where head is null

/* we are assuming that the head node is initially **null**
 when we initialise the linked list. */

Node temp = new Node();
temp.data = 2;

if(head == null) head = temp;
else {
    temp.next = head;
    head = temp;
}