DEV Community

Luckshvadhan B
Luckshvadhan B

Posted on

Remove Duplicates in Sorted Linked List

Approach:
Step 1 Take the linked list
Step 2 Traverse using current pointer
Step 3 If current value equals next value skip next node
Step 4 Else move forward
Step 5 Continue till end

Why this works???
List is sorted
so duplicates will be adjacent
we just remove consecutive same values

Code:
class ListNode:
def init(self,val=0,next=None):
self.val=val
self.next=next
def removeDuplicates(head):
curr=head
while curr and curr.next:
if curr.val==curr.next.val:
curr.next=curr.next.next
else:
curr=curr.next
return head

Limitation:
Only works for sorted list

Top comments (0)