Remove Duplicates from Sorted List
Easy · linked list
You are given the head of a singly linked list whose values are sorted in non-decreasing order, so equal values always sit next to each other.
Remove the extra copies so that every value appears exactly once, keeping the first node of each run of equal values. Return the head of the resulting list. The remaining values stay sorted.
An empty list stays empty. The nodes you receive are ListNode objects with a val and a next.
Examples
Example 1
Input: head = [2, 2, 5, 7, 7, 7, 9]
Output: [2, 5, 7, 9]
Each run of equal values shrinks to a single node: 2, 5, 7 and 9 remain.
Example 2
Input: head = [-4, -4, -4]
Output: [-4]
Example 3
Input: head = []
Output: []
Constraints
- 0 <= number of nodes <= 5000
- -10000 <= Node.val <= 10000
- The list is sorted in non-decreasing order.