Remove Elements from a Linked List by Index - Cant pass the test

Hi guys, I have noa idea why I am not able to pass the test. I guess I dont fully understand the task or sometning. Can anybody give me some hint…thank you very much.

My code so far


function LinkedList() {
var length = 0;
var head = null;

var Node = function(element){ // {1}
  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 {
      var currentNode = head;

      while(currentNode.next){
          currentNode  = currentNode.next;
      }

      currentNode.next = node;
  }

  length++;
};

// Only change code below this line
this.removeAt = function(index){
  if (index >= length || index < 0){return null}
  let currentNode = head;
  let previousNode;
  var c = 0;
  while (c !== index) {
      previousNode = currentNode;
      currentNode = currentNode.next;
      c++;
  }
  previousNode.next = currentNode.next;
  length--;
  return currentNode.element;//return removed element  
}
// Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36.

Challenge: Remove Elements from a Linked List by Index

Link to the challenge:
https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/remove-elements-from-a-linked-list-by-index

What happens on this line:

previousNode.next = currentNode.next;

when index is 0?

Thank you so much, I can see it now.

Now it is working great:

  this.removeAt = function(index){
    if (index >= length || index < 0){return null}
    let currentNode = head;
    if (index == 0){
      head = null;
      length--;
      return currentNode.element;
    }
    let previousNode;
    var c = 0;
    while (c !== index) {
        previousNode = currentNode;
        currentNode = currentNode.next;
        c++;
    }
    previousNode.next = currentNode.next;
    length--;
    return currentNode.element;//return removed element  
  }
1 Like

if (index == 0) the list is left with no head, but if there was more than one element then there should still be a head after removing the first element