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

183
Vistas
Why we don't update the head node of this linked list?

I was doing this Leetcode test https://leetcode.com/problems/add-two-numbers/ and the javascript solution that I found online is

var addTwoNumbers = function(l1, l2) {
    

    let carry = 0;
    let previousNode = new ListNode();
    let headNode = previousNode;
    while (l1 || l2 || carry) {
    let val1 = 0;
    let val2 = 0;
    if (l1) {
        val1 = l1.val;
        l1 = l1.next;
    }
    if (l2) {
        val2 = l2.val;
        l2 = l2.next;
    }
    let sum = val1 + val2 + carry;
    carry = sum > 9 ? 1 : 0;
    let digit = sum % 10;
    let currentNode = new ListNode(digit);
    previousNode.next = currentNode;
    previousNode = currentNode;
    }
        
return headNode.next;
}

I do not undestand how headNode gets updated and has the right answer. I mean:

Step1 - we create the new variable previousNode as {val:0 , next: null}
Step2 - headNode is previousNode, which means {val:0 , next: null}
Step3 - we create the new variable currentNode as {val:digit1 , next: null}
Step4 - previousNode.next is set as the currentNode, therefore previousNode now is {val:0 , next: {val:digit1 , next: null}}
Step5 - we set previousNode as the currentNode so we can continue adding the next solutions, and now previousNode is {val:digit1 , next: null}

and here we continue with the steps of the while loop

Step6 - we create the new variable currentNode as {val:digit2 , next: null}
Step7 - previousNode.next is set as the currentNode, therefore previousNode now is {val:digit1 , next: {val:digit2 , next: null}}
Step8 - we set previousNode as the currentNode, and now previousNode is {val:digit2 , next: null}

.... and so on ...

Now, question: when did we updated headNode??? why this code works and headNode is something like {val: 0, next : (everything we need)} , and therefore calling headNode.next we get the right solution?

Thank you for the explanation!

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