82. Remove Duplicates from Sorted List II
# Runtime: 40 ms, faster than 78.38%; Memory Usage: 14.2 MB, less than 99.93%
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return head
ahead = ListNode() # 建立哨兵节点
ahead.next = head
pre = ahead
tmp = head.val
head = head.next
flag = 0
while head:
if head.val == tmp:
flag = 1
head = head.next
else:
if flag: # 若存在重复时,则完全跳过重复部分,且保持原地
pre.next = head
else: # 若不存在重复时,则往前走一步
pre = pre.next
flag = 0
tmp = head.val
head = head.next
if flag:
pre.next = head
return ahead.next