编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:
输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:
链表长度在[0, 20000]范围内。
链表元素在[0, 20000]范围内。
进阶:
如果不得使用临时缓冲区,该怎么解决?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法:哈希表
使用哈希表来存储链表中每个数,然后遍历链表,如果它没有在哈希表中,那么加入;如果在哈希表中,那么将链表中该元素删除。头节点一定不会删除,所以用pos表示头节点,pos.next表示当前需要删除的节点。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeDuplicateNodes(self, head: ListNode) -> ListNode:
if not head:
return head
dic={head.val}
pos=head
while pos.next:
cur=pos.next
if cur.val not in dic:
dic.add(cur.val)
pos=pos.next
else:
pos.next=pos.next.next
return head