Writing LinkedList data structure in Javascript:
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
add(value) {
const newNode = {
value: value,
next: null
}
if(!this.head) {
this.head = newNode;
}
if(this.tail) {
this.tail.next = newNode;
}
this.tail = newNode;
}
}
const myLinedList = new LinkedList()
myLinedList.add('first value')
myLinedList.add('second values')
myLinedList.add('third values')
console.log(myLinedList)
… i don’t understand how head.next
appears as no null. How the next
for the head is written? I ask this because i add next
only here this.tail.next
but i don’t have any this.head.next
.