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

196
Visualizações
Recalling function on same input causing loops

Wrote the below function to merge two linkedlists:

var mergeTwoLists = function(l1, l2) {
    current = l1.head;    
    if (current === null){
        l1.head = l2.head; //Have to use l1.head instead of current since if we assign current again to l2.head the current will just start pointing to l2.head and lose reference to l1.
    }    
    else{        
        while( current.next != null){            
            current = current.next;            
        }        
        current.next = l2.head;        
    }    
    return l1;
};

Creating two linked lists:

let l1 = new linkedlist();
let l2 = new linkedlist();
l1.insert(1);
l1.insert(2);
l1.insert(4);
l2.insertEnd(1);
l2.insertEnd(3);
l2.insertEnd(4);

Now i called the function twice:

let l3 = mergeTwoLists(l1,l2);
console.log(l3.show());
let l4 = mergeTwoLists(l1,l2);
console.log(l4.show())

The first show outputs the expected 4 2 1 1 3 4. However, the second call goes on an infinite loop and keeps outputting 4 2 1 1 3 4 1 3 4 1 3 4 1 3 4 ........

Why is this happening?

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

0

mergeTwoLists doesn't make copies of the list nodes. So after the first merge, the last node of l1 is the same as the last node of l2. When you merge them again, the next property of the last node in l2 now points to l2.head, resulting in a circular list, just as if you'd done mergeTwoLists(l2, l2).

If you don't want this to happen, you should define a copyList() function, and use

current.next = copyList(l2).head;
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