82:删除排序链表中的重复元素II
程序员文章站
2022-07-15 13:21:44
...
问题描述
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例
输入: 1->2->3->3->4->4->5
输出: 1->2->5
输入: 1->1->1->2->3
输出: 2->3
思路
安个头结点,遍历链表,如果重复则跳过即可。
AC代码
# 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:
if not head or not head.next:
return head
last = ListNode(None)
last.next = head
head = last
last = head
curs = head.next
while curs:
cursor = curs
count = 0
while cursor and cursor.val == curs.val:
count += 1
cursor = cursor.next
if count > 1:
last.next = cursor
curs = last.next
else:
curs = curs.next
last = last.next
head = head.next
return head