Problem Statement
Given a sorted singly linked list, remove duplicates (nodes with duplicate values) such that each element appears only once.
Note: Try not to use extra space. The linked list is already sorted.
Examples:
Input: 2 → 2 → 4 → 5
Output: 2 → 4 → 5
Input: 2 → 2 → 2 → 2 → 2
Output: 2
My Goal
For this problem, my goal was to:
Understand how duplicates appear in sorted linked lists
Remove duplicates without using extra memory
Traverse and modify linked list efficiently
Strengthen pointer manipulation skills
My Approach & Solution
I used a single traversal approach since the list is already sorted.
Idea:
Traverse the list using a pointer
Compare current node with next node
If values are same:
Skip the next node
Else:
Move forward
Solution Code (Python)
class ListNode:
def __init__(s, v=0, n=None):
s.val = v
s.next = n
def deleteDuplicates(h):
c = h
while c and c.next:
if c.val == c.next.val:
c.next = c.next.next
else:
c = c.next
return h
Explanation
Use pointer c to traverse
If duplicate found → skip next node
Else → move to next node
Continue until end of list
Top comments (0)