Grokking Data Structures & Algorithms for Coding Interviews

0% completed

Solution: Remove Duplicates from Sorted List

Problem Statement:

Given a sorted linked list, remove all the duplicate elements to leave only distinct numbers. The linked list should remain sorted, and the modified list should be returned.

Examples

Example 1:

  • Input: 1 -> 1 -> 2
  • Output: 1 -> 2
  • Justification: Since 1 is repeated, we remove the duplicate to leave a sorted list of unique numbers.

Example 2:

  • Input: 1 -> 2 -> 2 -> 3
  • Output: 1 -> 2 -> 3
  • Justification: Here, 2 is the duplicate element, and by removing it, we obtain a list containing only distinct elements.

.....

.....

.....

Like the course? Get enrolled and start learning!
senthil kumar

senthil kumar

· 2 years ago

Kindly add the main method and print method to avoid confusion and add clarity.

public void printList(ListNode head) {
    ListNode current = head;
    while (current != null) {
        System.out.print(current.val + " ");
        current = current.next;
    }
    System.out.println();
}

public static void main(String[] args) {
    Solution solution = new Solution();
    
    // Test Example 1
    ListNode head1 = new ListNode(1, new ListNode(1, new ListNode(2)));
    ListNode result1 = solution.deleteDuplicates(head1); // Expected: 1 -> 2
    solution.printList(result1);

    // Test Example 2
    ListNode head2 = new ListNode(1, new ListNode(2, new ListNode(2, new ListNode(3))));
    ListNode result2 = solution