Introduction
When working with linked lists, handling duplicates is a common task. This problem becomes easier when the list is already sorted because duplicate values will always appear next to each other.
Problem Statement
Given a sorted singly linked list remove all duplicate nodes so that each element appears only once.
Return the modified linked list.
Example
Input:
2 -> 2 -> 4 -> 5
Output:
2 -> 4 -> 5
Key Insight
Since the list is sorted:
- Duplicate elements will be adjacent
- So we only need to compare the current node with the next node
Approach
We traverse the linked list and:
- If current value == next value then skip the next node
- Else move forward
Steps
- Start from head
- While current and current.next exist:
- If values are same then remove duplicate
- Else move to next node
Python Implementation
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def remove_duplicates(head):
current = head
while current and current.next:
if current.val == current.next.val:
current.next = current.next.next # skip duplicate
else:
current = current.next
return head
Step-by-Step Example
For:
2 -> 2 -> 4 -> 5
- Compare 2 and 2 duplicate so remove one
- Move to 2 compare with 4 different
- Continue till end
Final result:
2 -> 4 -> 5
Key Points
- Works because list is sorted
- No extra space required
- Simple pointer manipulation
- Very common beginner problem
Conclusion
Removing duplicates from a sorted linked list is a straightforward problem once you understand how linked list pointers work. Since duplicates are adjacent we can solve it efficiently in a single pass.
Top comments (0)