Introduction
Removing duplicates from a sorted linked list is a common problem in data structures. Since the list is already sorted, duplicate elements appear next to each other, making it easier to remove them.
Problem Statement
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the modified linked list.
Approach
We can solve this problem using a simple traversal:
- Start from the head of the linked list
- Compare current node with the next node
- If both values are equal → skip the next node
- Move to the next node
- Repeat until the end of the list
Python Code
python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def deleteDuplicates(head):
current = head
while current and current.next:
if current.val == current.next.val:
current.next = current.next.next
else:
current = current.next
return head
## Example:
Input
1 -> 1 -> 2 -> 2 -> 3 -> 3
ouput
1 -> 2 -> 3
Top comments (0)