---
description: LeetCode 82
---

# Remove Duplicates from Sorted List II

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

class Solution:
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        """
        思路:
        1. 若 head 為空怎辦? 加 dummy node
        2. while 裡頭判斷式
        - 需要判斷 head.val == head.next.val
        所以 while head and head.next 不能少
        3. 指標先指 但 pre 先不要移動
         dummy -> 1-> 1-> 1 -> 2 -> 3 -> 3 : 
                               p         h
                      
        """
        dummy = pre = ListNode('#')
        dummy.next = head
        
        while head and head.next:
            if head.val == head.next.val:
                while head and head.next and head.val == head.next.val:
                    head = head.next
                head = head.next
                pre.next = head
            else:
                # pre.next = head
                pre = head
                head = head.next
        return dummy.next
```
