82. 删除排序链表中的重复元素 II - 力扣(LeetCode)
python
# 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: Optional[ListNode]) -> Optional[ListNode]:
# 创建一个哑节点,简化对头节点的处理
dummy = ListNode(0)
dummy.next = head
prev = dummy # 指向当前已处理的最后一个节点
while head:
# 检查当前节点是否是重复节点
if head.next and head.val == head.next.val:
# 跳过所有重复的节点
while head.next and head.val == head.next.val:
head = head.next
# 让 prev 跳过这些重复节点
prev.next = head.next
else:
# 如果当前节点不重复,移动 prev 指针
prev = prev.next
# 移动 head 指针
head = head.next
return dummy.next