# 哈希表+循环
class Solution:
def removeDuplicateNodes(self, head: ListNode) -> ListNode:
if not head:
return head
head_dict = {head.val}
pos = head
while pos.next:
temp = pos.next
if temp.val not in head_dict:
head_dict.add(temp.val)
pos = pos.next
else:
pos.next = pos.next.next
return head
# 集合+循环
class Solution:
def removeDuplicateNodes(self, head: ListNode) -> ListNode:
pre, cur = None, head
visited = set()
while cur:
if cur.val in visited:
pre.next = cur.next
else:
visited.add(cur.val)
pre = cur
cur = cur.next
return head
方法三:二重循环(会超时)
思路:进阶要求是,不使用临时缓存,那么从头节点开始二重循环即可。简单点说就是,时间换空间。
# 二重循环(会超时)
class Solution:
def removeDuplicateNodes(self, head: ListNode) -> ListNode:
cur = head
while cur:
pos = cur
while pos.next:
if pos.next.val == cur.val:
pos.next = pos.next.next
else:
pos = pos.next
cur = cur.next
return head