Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
Adding Last Node to a Linked List

I am learning how to add node to the linked list. The following is the correct code:

class NodeList {
    constructor(head = null){
        this.head = head 
        this.addLast = function (data) {
            
            let node = new Node(data)
            console.log(curr)
        
            if (this.head === null) {
                return this.head = node
            } else{
                let curr = this.head
                while(curr.next){
                    curr = curr.next
                }
                curr.next = node
               
            }
        }
    }
}

Initially,

i wrote the code as such:

class NodeList {
    constructor(head = null){
        this.head = head 
        this.addLast = function (data) {

            let node = new Node(data)
            console.log(curr)

            if (this.head === null) {
                return this.head = node
            } else{
                let curr = this.head
                while(curr.next){
                    curr = curr.next
                }
                curr.next = node

            }
        }
    }
}

The main difference is at the if statement. Instead of

if(this.head === null) { return this.head = node} 

I wrote

let curr = this.head

if(curr  === null) { return curr  = node}

However, the code doesn't work.

If I do something like

let nodeList = new Nodelist nodeList.addLast(2)

I expect to get head: Node {data: 2, next: null}. The first code achieved that purchase but the second code does not. I am confused why this is so. Both codes look the same. Can someone enlighten me?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda