-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlinear.py
34 lines (28 loc) · 897 Bytes
/
linear.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
from typing import List
# 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
copied_map = {}
cur = head
while cur:
copied_item = Node(cur.val)
copied_map[cur] = copied_item
cur = cur.next
dup_list = Node(0)
dup_cur = dup_list
cur = head
while cur:
copied_item = copied_map[cur]
if cur.next:
copied_item.next = copied_map[cur.next]
if cur.random:
copied_item.random = copied_map[cur.random]
cur = cur.next
return copied_map[head]