138 copy a list
This commit is contained in:
parent
ed633c85b7
commit
c944caec2e
BIN
138-240617-pass/.main.py.swp
Normal file
BIN
138-240617-pass/.main.py.swp
Normal file
Binary file not shown.
48
138-240617-pass/main.py
Normal file
48
138-240617-pass/main.py
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
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]
|
Loading…
Reference in New Issue
Block a user