Problem Statement: here
Solution:
- The list is already sorted, so duplicate values will always appear next to each other.
- Start from the head of the linked list and look at one node at a time.
- For each node, compare its value with the value of the next node.
- If both values are the same, it means a duplicate is found.
- Instead of keeping both, adjust the link so that the current node skips the duplicate and points directly to the next different node.
- If the values are different, simply move to the next node and continue checking.
- Repeat this process for the entire list until the end is reached.
- By doing this, all duplicate nodes are removed without using any extra space, and only unique elements remain in the list.
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
Top comments (0)