-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm138.py
47 lines (35 loc) · 1.06 KB
/
m138.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""
# 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 None
origNodes = {}
newNodes = []
newHead = Node(head.val)
origCurr = head
curr = newHead
indx = 0
origNodes[origCurr] = indx
newNodes.append(curr)
while origCurr.next :
indx += 1
origCurr = origCurr.next
origNodes[origCurr] = indx
curr.next = Node(origCurr.val)
curr = curr.next
newNodes.append(curr)
curr = newHead
origCurr = head
while origCurr :
if origCurr.random :
curr.random = newNodes[origNodes.get(origCurr.random)]
origCurr = origCurr.next
curr = curr.next
return newHead