Skip to content

Commit d63e420

Browse files
committed
feat: add copy list with random pointer in python
1 parent cdc1dc7 commit d63e420

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Definition for a Node.
2+
class Node:
3+
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
4+
self.val = int(x)
5+
self.next = next
6+
self.random = random
7+
8+
def copyRandomList(self, head: "Node") -> "Node":
9+
oldToCopy = {None: None}
10+
11+
cur = head
12+
while cur:
13+
copy = Node(cur.val)
14+
oldToCopy[cur] = copy
15+
cur = cur.next
16+
cur = head
17+
while cur:
18+
copy = oldToCopy[cur]
19+
copy.next = oldToCopy[cur.next]
20+
copy.random = oldToCopy[cur.random]
21+
cur = cur.next
22+
return oldToCopy[head]
23+
24+
print(copyRandomList([7,None],[13,0],[11,4],[10,2],[1,0])) # [[7,None],[13,0],[11,4],[10,2],[1,0]]

0 commit comments

Comments
 (0)