Remove Duplicates from Sorted List II
MediumTop Interview 150 Linked ListProblem
You get the head of a linked list whose values are sorted from smallest to largest.
Some values appear more than once.
Delete every node whose value is repeated, so that only values that appeared exactly once are left. Do not keep even one copy of a repeated value. Return the head of the resulting list, which is still sorted.
Constraints
- 0 ≤ number of nodes ≤ 30
- -100 ≤ Node.val ≤ 100
- The list is sorted in non-decreasing order
Examples: pick one to animate
Solutions
Time: cur only moves forward and visits each node once, either to keep it or to skip it.
Space: Only a dummy node and a few pointers are used. Nodes are unlinked in place.
Put a dummy before the head and keep prev on the last node that is certain to stay. When cur starts a run of equal values, remember the value, move cur past every copy, and point prev's next at the first node after the run. Otherwise the node is unique, so prev moves onto it. The dummy lets a repeated head be removed like any other run.