Fetching latest headlines…
Remove Duplicates In Sorted Linked List
NORTH AMERICA
πŸ‡ΊπŸ‡Έ United Statesβ€’March 22, 2026

Remove Duplicates In Sorted Linked List

1 views0 likes0 comments
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:

  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

Comments (0)

Sign in to join the discussion

Be the first to comment!