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

412
Visualizações
Remove Duplicates from Sorted List in Javascript

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Input: head = [1,1,2] Output: [1,2]

Solution:

    let curr=head;
    while(curr && curr.next){
        
        if(curr.val===curr.next.val){
            curr.next=curr.next.next;
        }
        else{
            curr=curr.next;
        }
    }
 return head;

I am trying to solve this question on leetcode and found one solution which I am not able to understand one thing, Why are we taking the head in let curr? And, If I am trying to do the same thing without takinghead in another variable then I am getting only [2] as output.

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

0

Why are we taking the head in let curr?

For two reasons:

  1. curr needs to be initialised to something, otherwise it will have an undefined value, making the while condition always false, so there will be no iterations and no removals happening.

  2. curr is intended to refer to each (non-duplicate) node one after the other, so it makes sense to start with the first node, which is head.

And, If I am trying to do the same thing without taking head in another variable then I am getting only [2] as output.

That could only happen when you also change the return head by return curr. If you do that, then you will always return a list that has no more than one node, because after the loop has completed, curr will refer to the last node in the list (if it is not empty).

In order to return all nodes in a list, you need to always return its first node, and that is what head represents.

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