"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
old_to_new_map ={}# key 是老节点, value 是新节点
if not head:
return None
cur=head
#遍历原本
while cur :
new_node =Node(cur.val)
old_to_new_map[cur]=new_node
cur=cur.next
#做第二次的扫描
cur= head
while cur :
new_node=old_to_new_map[cur]
new_node.next=old_to_new_map.get(cur.next)
new_node.random=old_to_new_map.get(cur.random)
cur=cur.next
return old_to_new_map[head]
深拷贝需要先创建独立的节点, 然后通过hashmap映射的方式,把新旧节点对应起来,这样 调用旧节点的next和random指针引用,就同步能引射到新节点彼此之间的next和random指针引用。