82. 删除排序链表中的重复元素 II

https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/

解法一:

用pre记录前驱,i往后遍历,遇到重复的就继续向前,直到非重复,然后修改pre的后继即可

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        Head = ListNode(0)
        Head.next = head
        pre, i = Head, head    #前驱和工作节点
        while i:
            while i.next and i.val == i.next.val:    #若有重复,跳到最后一个重复节点
                i = i.next
            if pre.next != i:    #说明有重复
                pre.next = i.next
            else:
                pre = i
            i = i.next
        return Head.next

最后更新于