Description

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:

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

Example 2:

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

Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

Solution

The problem mentions as a constraint that the list is ascending order. So, we can simply iterate through the list and check for next element value. If the next has the same value as current node, we simply move the next of current to current.next.next.

 1class Solution {
 2    public ListNode deleteDuplicates(ListNode head) {
 3        ListNode current = head;
 4        while (current != null && current.next != null) {
 5            if (current.val == current.next.val) {
 6                current.next = current.next.next;
 7            } else {
 8                current = current.next;
 9            }
10        }
11        return head;
12    }
13}
  • Time Complexity: O(n)
  • Space Complexity: O(1)