
Remove Duplicates in Sorted Linked List
In this task, I worked on removing duplicate elements from a sorted linked list . Since the list is already sorted, duplicate values will always appear next to each other. What I Did I created a function removeDuplicates that: Takes the head of a linked list Removes duplicate nodes Returns the modified list with only unique elements How I Solved It Instead of using extra space , I used a simple pointer traversal . Approach I used one pointer: curr → starts from the head and traverses the list Logic Behind It At each step: Compare the current node with the next node If both values are the same: Skip the next node → curr.next = curr.next.next Otherwise: Move to the next node → curr = curr.next Code class ListNode : def __init__ ( self , val = 0 , next = None ): self . val = val self . next = next def removeDuplicates ( head ): curr = head while curr and curr . next : if curr . val == curr . next . val : curr . next = curr . next . next else : curr = curr . next return head How It Works B
Continue reading on Dev.to
Opens in a new tab


