Why it works
- The list is sorted, so the copies of a value stand side by side: one look at cur.next tells whether cur repeats, and cur then walks past every copy of dup.
- prev only moves onto a node known to have no copy, so prev.next = cur cuts out all the copies with one link, the first one included.
- The dummy is a node before the head that can never be deleted. Here the head 2 repeats, and dummy.next simply becomes 5.
Complexity
Time O(n): cur only moves forward, one step per node. Memory O(1): two pointers and the dummy.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗