I try to understand how push() method works with the use of tails in JS. here is the code:
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class SinglyLinkedList {
constructor() {
this.length = 0;
this.head = null;
this.tail = null;
}
push(val) {
const newNode = new Node(val)
if (this.head===null) { // happens only once
this.head = newNode;
this.tail = this.head;
} else {
this.tail.next = newNode; // this.a.next = b node???
this.tail = newNode;
}
this.length++
}
specifically, I don't understand the else part inside the push() method. How does each next of a head gets assigned a new node if we say this.tail.next = newNode? Where is the relation between head and tail and how by saying this.tail.next = newNode we get access to the head property of the list? When I run this code, it works perfectly correct and it confuses me.
const myList = new SinglyLinkedList();
myList.push("111");
myList.push("222");
myList.push("333");
console.log(myList);
Output:
SinglyLinkedList {
length: 3,
head: Node { val: '111', next: Node { val: '222', next: [Node] } },
tail: Node { val: '333', next: null } }