49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
|
class Solution:
|
||
|
def copy RandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
|
||
|
l = []
|
||
|
cur = head
|
||
|
while cur != None:
|
||
|
l.append(cur)
|
||
|
cur = cur.next
|
||
|
n_l = []
|
||
|
for i in range(len(l)):
|
||
|
tmp = Node()
|
||
|
tmp.val = l[i].val
|
||
|
n_l.append(tmp)
|
||
|
for i in range(len(l)):
|
||
|
if l[i].random == None: continue
|
||
|
n_l[i].random = n_l[l[i].random.val]
|
||
|
if i == len(l) - 1: continue
|
||
|
n_l[i].next = n_l[i+1]
|
||
|
return n_l[0]
|
||
|
"""
|
||
|
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 head == None:
|
||
|
return None
|
||
|
l = []
|
||
|
cur = head
|
||
|
cnt = 0
|
||
|
m = {}
|
||
|
while cur != None:
|
||
|
l.append(cur)
|
||
|
m[cur] = cnt
|
||
|
cur = cur.next
|
||
|
cnt += 1
|
||
|
n_l = []
|
||
|
for i in range(len(l)):
|
||
|
tmp = Node(l[i].val)
|
||
|
n_l.append(tmp)
|
||
|
for i in range(len(l)):
|
||
|
if i != len(l) - 1: n_l[i].next = n_l[i+1]
|
||
|
if l[i].random == None: continue
|
||
|
n_l[i].random = n_l[m[l[i].random]]
|
||
|
return n_l[0]
|