思路
先将链表元素依次存入数组中,然后使用计数器统计每个元素的出现次数。仅保留在数组中出现次数为 1 的元素用于重新构建链表,最后返回新链表的头节点即可。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
cur=head
res=[]
while cur:
res.append(cur.val)
cur=cur.next
output=[]
count=Counter(res)
for key,val in count.items():
if val==1:
output.append(key)
dummy=ListNode()
cur=dummy
for i in range(len(output)):
p=ListNode(output[i])
cur.next=p
cur=p
return dummy.next