利用一个虚拟头节点,和维护一个前置节点.
# 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