Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
Inserting element into specific index in a Linked List (Javascript)

I cannot figure out why my code isn't working and I've been staring at it forever. When I try to call the function, I get the error "Cannot read properties of null (reading 'next')" and wouldn't have expected this to happen since I am re-assigning both curr and prev to iterate through the list.

// insert an item at the position specified
LinkedList.prototype.insert = function(data, position) {
  let newNode = new Node(data); //instantiate a new node
  if (position < 0 || position > this.size) { // if the position is less than zero or greater than the size of the linked list itself
    return 'Please enter a valid position.' // return error statement
  } else {
    if (this.head === null) { // if we do not have any nodes in the list)
      this.head = newNode; // point newNode's pointer to the head
      this.tail = newNode; // point the head pointer to the newNode;
    } else {
      let prev = null; // set up a variable to hold the prev value
      let curr = this.head; // set a current variable to this.head (the start)
      let currIndex = 0;
      while (currIndex < position) { // while the current index we're at is less than the position, we need to keep iterating
        prev = curr; // set prev variable equal to curr
        curr = curr.next; // skip to next node until we find the right position
      }
      newNode.next = curr; // after we find the position, set the new node's next to equal the current
      prev.next = newNode; // also set the previous node's next to equal the new node
    }
    this.size++;
  }
}

console.log(myList)
myList.insert(4,1)
console.log(myList)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Closing this out as I figured out what was wrong. I was forgetting to increment currIndex within the while loop, haha.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda