Leetcode 82. Remove Duplicates from Sorted List II

利用一個虛擬頭節點,和維護一個前置節點.spa

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        dummy=pre=ListNode(0)
        pre.next=head
        
        while head and head.next:
            v=head.val
            if head.next.val!=v:
                head=head.next
                pre=pre.next
            else:
                while head and head.val==v:
                    head=head.next
                    if not head:
                        break
                pre.next=head
        return dummy.next
            
        
相關文章
相關標籤/搜索