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

Longest Substring Without Repeating Characters Java Program - The Coding Shala

Anti Diagonals - The Coding Shala

First Missing Positive Solution - The Coding Shala

Shell Script to Display the digits which are at odd positions in a given 5-digit number - The Coding Shala

Java Program to Reverse a String using Stack - The Coding Shala