给定一个已排序的链表的头 head
, 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
这里最重要的就是判断cur.next和cur.next.next是否相等,相等的话,保存该值然后循环删除等于该值的节点。同时还需要注意判断这两个节点是否存在,可能会遇到头结点,采用虚节点的方式。
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None:
return head
dummy_head = ListNode(0,head)
cur = dummy_head
# num = 0
while cur.next and cur.next.next:
if cur.next.val == cur.next.next.val:
x = cur.next.val
while cur.next and cur.next.val == x:
cur.next = cur.next.next
else:
cur = cur.next
return dummy_head.next