Remove Duplicates from Sorted Linked List - The Coding Shala

Home >> Interview Prep >> Remove Duplicates from Sorted Linked List

 In this post, we will learn how to Remove Duplicates from Sorted Linked List in Java.

Remove Duplicates from Sorted Linked List Problem

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Example 1:
Input: head = [1,1,2]
Output: [1,2]

Example 2:
Input: head = [1,1,2,3,3]
Output: [1,2,3]

Remove Duplicates from Sorted Linked List Java Solution

Approach 1

Iterative method.

Time Complexity: O(n)
Space Complexity: O(1)

Java Program: 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null) return head;
        
        ListNode current = head;
        
        while(current.next != null) {
            
            //check for duplicates
            if(current.val == current.next.val) {
                //if duplicate then skip next
                current.next = current.next.next;
            } else {
                current = current.next;
            }
            
        }
        return head;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala