forked from super30admin/Design-5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcopylist.py
28 lines (28 loc) · 824 Bytes
/
copylist.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# // Time Complexity :O(n)
# // Space Complexity :O(n)
# // Did this code successfully run on Leetcode :Yes
# // Any problem you faced while coding this :NO
"""
# Definition for a Node.
class Node:
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if head is None: return None
mapping = {}
cur = head
while cur:
mapping[cur] = Node(cur.val,None,None)
cur = cur.next
cur = head
while cur:
if cur.next:
mapping[cur].next = mapping[cur.next]
if cur.random:
mapping[cur].random = mapping[cur.random]
cur = cur.next
return mapping[head]