题目:
删除排序链表中的重复元素 II:给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
思路:
懒人思维,使用哈希表。
程序:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return None
myHashMap = dict()
myNode = head
while myNode:
if myNode.val in myHashMap:
myHashMap[myNode.val] = myHashMap.get(myNode.val, 0) + 1
else:
myHashMap[myNode.val] = myHashMap.get(myNode.val, 1)
myNode = myNode.next
myNewNode = head
myNewHead = None
myNewCurrent = None
while myNewNode:
if myHashMap[myNewNode.val] == 1:
node = ListNode(myNewNode.val)
if myNewHead is None:
myNewHead = node
myNewCurrent = myNewHead
else:
myNewCurrent.next = node
myNewCurrent = myNewCurrent.next
myNewNode = myNewNode.next
return myNewHead