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

191
Visualizações
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 à 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