LeetCode 82. Remove Duplicates from Sorted List II 2019-06-15

题目描述

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。

tag

链表

样例

1
2
输入: 1->2->3->3->4->4->5
输出: 1->2->5

算法1

(指针操作) O(n)
思路
复杂度分析:
python 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
dummy = ListNode(0)
dummy.next = head
pre = dummy
while head and head.next:
if head.val == head.next.val:
while head and head.next and head.val == head.next.val:
head = head.next
head = head.next
# 此时head跳过所有一样元素值的节点
pre.next = head
else:
# 此时 head 与 head.next 值不一样,所以pre要保留
# 所以都向后一步,pre是保留,head是继续考察
pre = pre.next
head = head.next
return dummy.next