Q:
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5 输出: 1->2->5
示例 2:
输入: 1->1->1->2->3 输出: 2->3
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/description/
思路:先求出重复元素 再删除 没啥效率
代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
tmp = []
h = head
dic = {}
while h:
if h.val in dic:
tmp.append(h.val)
else:
dic[h.val] = 1
h = h.next
print (tmp)
h_ = ListNode(-1) # head
h_.next = head
cur = h_
while cur.next:
delNode = cur.next
if delNode.val in tmp:
cur.next = delNode.next
else:
cur = cur.next
return h_.next