All problems

Remove Duplicates from Sorted List II

Medium · linked list

You are given the head of a singly linked list whose values are sorted in ascending order (equal values sit next to each other).

Remove every value that appears more than once, so that not even one copy of it is left. Only values that appeared exactly once stay. Return the head of the resulting list, with the surviving nodes in their original order. If nothing survives, return an empty list.

The nodes you receive are ListNode objects with a val and a next.

Examples

Example 1

Input: head = [1, 2, 2, 3, 4, 4, 5]

Output: [1, 3, 5]

The values 2 and 4 each appear twice, so both copies of each are removed.

Example 2

Input: head = [6, 6, 6, 7]

Output: [7]

Example 3

Input: head = [3, 3, 8, 8]

Output: []

Every value repeats, so nothing is left.

Constraints