def deleteDuplicates(head: ListNode) -> ListNode:
if not head:
return head
dummy = ListNode(0)
dummy.next = head
cur = head.next
while cur:
if cur.val != head.val:
head.next = cur
head = cur
else:
head.next = None # 如果当前值与head的值相等,需要断开
cur = cur.next
return dummy.next
def deleteDuplicates2(head: ListNode) -> ListNode:
cur = head
while cur and cur.next: # 如果不是最后一个,cur为None是排除[]的情况
if cur.val == cur.next.val:
cur.next = cur.next.next # delete duplicate element
else:
cur = cur.next
return head
leecode——remove duplicate elements(83)
最新推荐文章于 2021-07-31 23:42:29 发布