VOOZH about

URL: https://dev.to/dharani_boominathan_b1e6b/remove-duplicates-in-sorted-linked-list-7lk

⇱ Remove Duplicates In Sorted Linked List - DEV Community


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:

  1. Start from the head of the linked list
  2. Compare current node with the next node
  3. If both values are equal → skip the next node
  4. Move to the next node
  5. 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