解题思路
每个节点有三种情况
1.前面有重复的节点
2.后面有重复的节点
3.前后都没有重复的节点
只保留第三种!
82. 删除排序链表中的重复元素 II
代码
# 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:
ans = tail = ListNode(0)
dup_val = None
while head:
if head.val == dup_val: # 前面有重复
head = head.next
continue
elif head.next and head.val == head.next.val: # 后面有重复
dup_val = head.val
head = head.next
continue
else: # 前后都没有重复
tmp = head.next
# 插入返回值尾部
tail.next = head
tail = head
head = tmp
tail.next = None
return ans.next
效果图
网友评论