
# 🧩 Remove Duplicates from Sorted Linked List (Java)
🚀 Problem Statement You are given the head of a sorted singly linked list . Your task is to: Remove all duplicate nodes Keep only one occurrence of each value Do it in-place (no extra space) 💡 Key Idea Since the list is already sorted , duplicates will always be adjacent . 👉 So we just: Traverse the list Compare current node with next node If equal → skip the next node 🧠 Approach Start from the head While current node and next node exist: If current.data == current.next.data Remove next node → current.next = current.next.next Else move forward Return the head 🛠️ Java Implementation (GFG Style) ```java id="r8p4kx" class Solution { // Function to remove duplicates from sorted linked list Node removeDuplicates(Node head) { // Base case if (head == null) return null; Node current = head; while (current != null && current.next != null) { if (current.data == current.next.data) { // Skip duplicate node current.next = current.next.next; } else { current = current.next; } } return head; } } ---
Continue reading on Dev.to Beginners
Opens in a new tab


