Data Structures - Remove Elements from a Linked List by Index

Tell us what’s happening:
Not exactly sure what I’m doing wrong. I’ve whiteboarded the problem and visualized my code using pythontutor, and while it makes sense to me, it’s not producing a correct result on the website.

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 {
      var currentNode = head;

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

      currentNode.next = node;
    }

    length++;
  };

  // Only change code below this line
  this.removeAt = (index) => {
    if (index < 0 || index >= length) {
      return null
    }
    if (index === 0) {
      let removedNode = head
      head = head.next
      length--
      return removedNode.element
    } else {
      let count = 1
      let prev = head
      let curr = prev.next
      while (count + 1 !== index) {
        prev = prev.next
        curr = curr.next
        count++
      }
      prev = prev.next
      curr = curr.next
      prev.next = curr.next
      length--
      return curr.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/116.0.0.0 Safari/537.36

Challenge: Data Structures - Remove Elements from a Linked List by Index

Link to the challenge:

Take a look at the example below. I’m getting TypeError when trying to remove element from index 1. Other indices are removed without issues.

const l = new LinkedList();
l.add(1);
l.add(2);
l.add(3);
l.add(4);

console.log(l.head());
console.log(l.removeAt(1));   // TypeError: Cannot read properties of null (reading 'next')
1 Like

I GOT IT! The bug was at line 49. I changed
while (count + 1 !== index)
to instead be
while (count + 1 < index)
and it worked. Thanks!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.