题目
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。 示例 1:
输入: 1->2->3->3->4->4->5 输出: 1->2->5 示例 2:
输入: 1->1->1->2->3 输出: 2->3
代码
可能会删除头节点,所以设立一个哨兵节点
# 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:
"""
可能会删除头节点,所以设立一个哨兵节点
"""
dummy = ListNode(0)
dummy.next = head
head = dummy
while head.next and head.next.next:
if head.next.val == head.next.next.val: # 判断下两个节点的值是否相同
val = head.next.val # 相同的话记录相同的值
while head.next and head.next.val == val: #
head.next = head.next.next
else:
head = head.next
return dummy.next