82. Remove Duplicates from Sorted List II

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

双指针遍历,对比节点值。

  • 因为值重复的节点需要全部删掉(不保留distinct),所以对比完成后,多了一个删掉前节点的操作。而且因为 head 节点也可能被删除,需要设置 dummy head 来记录表头。

  • 注意随时检查指针的存在性。

  • 由于两个指针之间距离是保持固定的,所以也可以用单指针的写法。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        dummy = ListNode()
        dummy.next = head
        if not dummy.next or not dummy.next.next:
            return head
        i, j = dummy, dummy.next.next
        while j:
            if i.next.val == j.val:
                while j and i.next.val == j.val:
                    j = j.next
                    i.next.next = j
                i.next = j
                if not j: break 
            else:
                i = i.next
            j = j.next
        return dummy.next
        

Last updated

Was this helpful?