Problem
Given a sorted singly linked list, remove duplicate nodes so that each element appears only once.
Do not use extra space.
The linked list is already sorted, so duplicates will be adjacent.
Example 1
Input: 2 -> 2 -> 4 -> 5
Output: 2 -> 4 -> 5
Explanation: The value 2 appears twice, so one duplicate is removed.
Example 2
Input: 2 -> 2 -> 2 -> 2 -> 2
Output: 2
Explanation: All nodes have value 2, so only one node remains.
Approach
Start from the head node.
Traverse the linked list.
If the current node value is equal to the next node value, skip the next node.
Otherwise move to the next node.
Continue until the end of the list.
Python Code
def removeDuplicates(head):
curr = head
while curr and curr.next:
if curr.data == curr.next.data:
curr.next = curr.next.next # remove duplicate
else:
curr = curr.next # move forward
return head
Output
2 -> 4 -> 5
Top comments (0)