复杂链表的复制
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null
参考
"""
# 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: 'Node') -> 'Node':
if not head:
return
hash = {}
tem = head
while tem:
hash[tem] = Node(tem.val)
tem = tem.next
tem = head
while tem:
hash[tem].next = hash.get(tem.next)#注意要用get来获取key的vale,这样如果为none,会返回none;用[]会报错
hash[tem].random = hash.get(tem.random)
# hash[tem].next = hash[tem.next]
# hash[tem].random = hash[tem.random]
tem = tem.next
return(hash[head])