从未排序的链表中删除重复项
给定N
节点的未排序链表。任务是从这个未排序的链表中删除重复的元素。当一个值出现在多个节点中时,应保留最先出现的节点,并删除所有其他重复节点。
示例1:
输入:
N=4
值[]={5,2,2,4}
输出:5 2 4
示例2:
输入:
N=5
值[]={2,2,2,2}
输出:2
我的代码
def removeDuplicates(head):
if head is None or not head.next:
return head
d = {}
curr = head
prev = None
while curr.next:
prev = curr
curr = curr.next
if curr.data in d:
prev.next = curr.next
else:
d[curr.data] = 1
return head
在while循环中,作为条件,您需要curr
而不是curr.next
。并且您需要在while循环结束时覆盖curr
。像这样:
def removeDuplicates(head):
if head is None or not head.next:
return head
d = {}
curr = head
prev = None
while curr:
if curr.data in d:
prev.next = curr.next
else:
d[curr.data] = 1
prev = curr
curr = curr.next
return head