算法1
时间复杂度$O(2n)$
先走一遍,查找所有重复的元素,用一个集合set来存储
再从头走一遍,若节点的值不在集合set中,将其添加到新的链表中
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplication(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
mask = set()
dummy = ListNode(0)
dummy.next = head
while head: # 先走一遍,将重复元素加入到集合mask中
if head.next and head.next.val == head.val:
mask.add(head.val)
head = head.next.next
else:
head = head.next
head = dummy.next
res = dummy
res.next = None
while head: # 再走一遍,将不在集合mask中的元素加入到链表中
if head.val in mask: # 若该节点是重复节点,不加
head = head.next
else:
current = head.next
head.next = res.next
res.next = head
head = current
res = res.next
return dummy.next
算法2
双指针 $O(n)$
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplication(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
p = dummy
while p.next:
q = p.next
while q and p.next.val == q.val:
q = q.next
if p.next.next == q:
p = p.next
else:
p.next = q
return dummy.next