题目:
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 2->3
分析:
- 利用字典记录每个数字出现的次数
- 创建一个新的链表,将出现次数为1的加入到新链表中
代码:
# 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 head
dicts = {} # 记录出现的次数
res = [] # 出现一次的数组
while head:
if head.val not in dicts:
dicts[head.val] = 1
else:
dicts[head.val] += 1
head = head.next
for k,v in dicts.items():
if v == 1:
res.append(k)
res.sort() # 排序
heads = pos = ListNode(None)
for i in res:
pos.next = ListNode(i)
pos = pos.next
return heads.next
结果: