82. Remove Duplicates from Sorted List II
# medium
Key idea: skip all same elements until different one then move forward
核心:跳过所有相同的元素,直到碰到不同的元素再继续往前走
Solution 1(complicated version):
head
points current node, oncehead.val == head.next.val
, it deletes all duplicates except itself.pre
records pre-node ofhead
and helps delete the first duplicates.if not encounter duplicates, both of
pre
andhead
move one step.
Dummy note and pre-node are necessary. flag
is needed to judge head
is the last duplicate or nor. When last node is duplicate node, don't forget to let pre.next = null
because pre
represents the whole new list.
Solution 2(easy version):
head
represents new list.record duplicates value and delete all duplicates until
head.next.val != head.next.next.val
.otherwise head move one step.
Don't move head
until ensure the next element is not duplicated.
Last updated