82. Remove Duplicates from Sorted List II
# medium
Key idea: skip all same elements until different one then move forward
核心:跳过所有相同的元素,直到碰到不同的元素再继续往前走
Solution 1(complicated version):

headpoints current node, oncehead.val == head.next.val, it deletes all duplicates except itself.prerecords pre-node ofheadand helps delete the first duplicates.if not encounter duplicates, both of
preandheadmove 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.
head 永远指向当前节点,一旦后一个节点与当前节点相同,则删除后一个节点,直到遇到不同的节点
pre 记录当前节点的前一个节点,当删除除了第一个外所有重复节点,pre帮助删除这个节点
如果没有遇到重复,pre和head同时往后挪一位
虚拟节点和前置节点非常必要;需要一个flag标志位判断head是否是最后一个重复元素;当最后一个节点是重复节点时,要将pre.next=null,因为pre才是新的list。
Solution 2(easy version):

headrepresents new list.record duplicates value and delete all duplicates until
head.next.val != head.next.next.val.otherwise head move one step.
head表示新list记录重复元素的值,并且一次删除所有重复直到
head.next.val != head.next.next.val否则
head往后一步
If deleting all duplicates required, we can record the value and delete them in on time; If deleting all duplicates except itself required, we can keep first one and delete others.
Last updated
Was this helpful?