copy list with random pointer
"""
# 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]':
if not head:
return
map = {}
def getnode(cur):
if cur not in map:
map[cur] = Node(cur.val)
return map[cur]
cur = head
while cur:
node = getnode(cur)
if cur.next:
node.next = getnode(cur.next)
if cur.random:
node.random = getnode(cur.random)
cur = cur.next
return getnode(head)
Last updated