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

思路
第一种做法,用hash-set存储出现过的值。
枚举待移除节点的前驱节点。(因为直接枚举待移除节点,本自杀是将它的前驱节点连向后继节点。进一步,由于是链表结构,无法直接范围一个节点的前驱节点。因此考虑枚举待移除节点的前驱节点。)
使用临时缓冲区,其实就是时间换空间的做法,使用两层循环。不推荐!
代码
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution:def removeDuplicateNodes(self, head: ListNode) -> ListNode:# hash表if not head:return headnode = headhash_set = {node.val}while node.next:cur = node.nextif cur.val not in hash_set:hash_set.add(cur.val)node = node.nextelse:node.next = node.next.nextreturn head
