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.
CodePudding user response:
Why are we taking the
head
inlet curr
?
For two reasons:
curr
needs to be initialised to something, otherwise it will have an undefined value, making thewhile
condition always false, so there will be no iterations and no removals happening.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 ishead
.
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.