题目

编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。

image.png

思路

第一种做法,用hash-set存储出现过的值。

枚举待移除节点前驱节点。(因为直接枚举待移除节点,本自杀是将它的前驱节点连向后继节点。进一步,由于是链表结构,无法直接范围一个节点的前驱节点。因此考虑枚举待移除节点的前驱节点。)

使用临时缓冲区,其实就是时间换空间的做法,使用两层循环。不推荐!

代码

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def removeDuplicateNodes(self, head: ListNode) -> ListNode:
  8. # hash表
  9. if not head:
  10. return head
  11. node = head
  12. hash_set = {node.val}
  13. while node.next:
  14. cur = node.next
  15. if cur.val not in hash_set:
  16. hash_set.add(cur.val)
  17. node = node.next
  18. else:
  19. node.next = node.next.next
  20. return head