This is the code I have written so far. I don't think I am necessarily on the right track using a loop in the 'Node' function...
function LinkedList() {
this.head = null;
this.tail = null;
this.length = 0;
}
function Node(...val) {
if (Array.isArray(val)) {
for (let i = 0; i < val.length; i++) {
this.push(val[i])
}
}
this.value = val;
this.next = null;
}
LinkedList.prototype.push = function(val) {
let newNode = new Node(val);
if(!this.head) {
this.head = newNode;
return this.head;
}
let tail = this.head;
while (tail.next !== null) {
tail = tail.next;
}
tail.next = newNode;
return this.head;
};
Here are the tests I am trying to run on it...
const newList = new LinkedList(5, 1, 2, 6, 8);
console.log(newList.head.value);
console.log(newList.head.next.value);
console.log(newList.head.next.next.value);
console.log(newList.head.next.next.next.value);
console.log(newList.head.next.next.next.next.value);
console.log(newList.head.next.next.next.next.next);
The output of the console logs is just "Cannot read properties of null (reading 'value').
Can someone point out what I am doing wrong or where to head next? Thank you for your time!