Originally published byDev.to
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
πΊπΈ
More news from United StatesUnited States
NORTH AMERICA
Related News
CBS News Shutters Radio Service After Nearly a Century
3h ago
Officer Leaks Location of French Aircraft Carrier With Strava Run
3h ago
White House Unveils National AI Policy Framework To Limit State Power
3h ago
Microsoft Says It Is Fixing Windows 11
3h ago
Can Private Space Companies Replace the ISS Before 2030?
3h ago