因为可能删除头结点,所以我们采用dummy哑结点(跟上一篇类似)
dummy初始化
dummy=ListNode(0,head)
# 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,head)
cur=dummy
#起码得有next和next.next
while cur.next and cur.next.next:
val=cur.next.val
if cur.next.next.val==val:
#这个时候已经有重复的了,我们使用一个while循环不断删除这个值
while cur.next and cur.next.val==val:
cur.next=cur.next.next
#否则,移动cur即可
else:
cur=cur.next
return dummy.next
灵神牛啊