I'm just a little bit confuse here, I want to know what is really happening. I'm following a tutorial for DS&A for Javascript -> https://www.youtube.com/watch?v=BVJv_AiXSGg&t=495s (51:21 part). I'm asking it here because it wasn't mentioned in the tutorial.
Here is the class for Node:
class NodeClass {
constructor(value) {
this.value = value;
this.next = null;
}
}
And here is the class for actual linked list:
class LinkedList {
constructor(value) {
const newNode = new NodeClass(value);
this.head = newNode;
this.tail = this.head;
this.length = 1;
}
push(value) {
const newNode = new NodeClass(value);
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
}
printing:
let myLinkedList = new LinkedList(7);
myLinkedList.push(4);
console.log(myLinkedList);
Now the tricky part for me and the one I really confused is the output
LinkedList {
head: NodeClass { value: 7, next: NodeClass { value: 4, next: null } },
tail: NodeClass { value: 4, next: null },
length: 2
}
As you can see, the "next" property had an object value which is "{ value: 4, next: null }" But the one that I don't understand is I did not do "this.head.next", and yet it is working fine.
Can you please help me to understand what's going under the hood about this one.
Furthermore, if I push more more more data it works totally fine as expected. Thank you !