利用一个虚拟头节点,和维护一个前置节点.
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:def deleteDuplicates(self, head: ListNode) -> ListNode:if not head or not head.next:return headdummy=pre=ListNode(0)pre.next=headwhile head and head.next:v=head.valif head.next.val!=v:head=head.nextpre=pre.nextelse:while head and head.val==v:head=head.nextif not head:breakpre.next=headreturn dummy.next