Tell us what’s happening:
Don’t pass the test: “Your remove
method should reassign the reference of the previous node of the removed node to the removed node’s next
reference.”
Error: “Cannot read property ‘next’ of null”.
I don’t see, where may be an error and why item (or element) is null.
I’ve try to make a checking the case, if we have no such element in List by if (item.next == null) return;
into while
. In this case the “Cannot read property ‘next’ of null” was not showed, but test same didn’t pass.
Your code so far
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){
this.element = element;
this.next = null;
};
this.size = function(){
return length;
};
this.head = function(){
return head;
};
this.add = function(element){
var node = new Node(element);
if(head === null){
head = node;
} else {
let currentNode = head;
while(currentNode.next){
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
this.remove = function(element){
// Only change code below this line
let item = head;
if(item.element == element) head = item.next;
else {
while (item.next != element) {
item = item.next;
}
item.next = element.next;
}
length--;
// Only change code above this line
};
}
Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/data-structures/remove-elements-from-a-linked-list