Remove Elements from a Linked List - element is null

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

Well, after some tested I found next:

  1. Linked List is not like a chain obj1 . obj2 . obj3,
    but like a lot of nested objects:
obj1 {
   obj2 {
     obj3
  }
}
  1. In stdin we have a string. Detected correct item should be the object.

So, the working code looks so:

      while (item.next.element != element) {
        if (item.next == null) return 'null';
        item = item.next;
      }
      item.next = item.next.next;
2 Likes