Hey there, still new to data structures and had some problems working with linked lists. The FCC challenge is here: https://learn.freecodecamp.org/coding-interview-prep/data-structures/create-a-linked-list-class
When trying to set the inputted node element as the Node.next of an existing element, I ran into trouble. My code is here:
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){
this.element = element;
this.next = null;
};
this.head = function(){
return head;
};
this.size = function(){
return length;
};
this.add = function(element){
// Only change code below this line
let newNode = new Node(element);
if(length == 0){
head = newNode;
length = 1;
}
else{
let nextNode = head;
for(let i=0; i<length; i++){
nextNode = nextNode.next;
}
nextNode = newNode;
length += 1;
}
// Only change code above this line
};
}
When I submit, I get an error “Cannot read property ‘element’ of null”, which leads me to think that ‘head’ is still pointing to ‘null’ somehow, even though my solution already passed the test for setting head to new Node(). I’m not really sure what to do