Skip to content

Commit e0947f1

Browse files
committedOct 27, 2024
re-solve "138. Copy List with Random Pointer"
1 parent 447d34c commit e0947f1

File tree

1 file changed

+17
-22
lines changed

1 file changed

+17
-22
lines changed
 

‎src/copy_list_with_random_pointer.py

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,39 +4,34 @@
44
class Node:
55
def __init__(
66
self, x: int, next: Node | None = None, random: Node | None = None
7-
):
7+
) -> None:
88
self.val = int(x)
99
self.next = next
1010
self.random = random
1111

12-
def __str__(self) -> str:
13-
return f"Node({self.val})"
14-
1512

1613
class Solution:
1714
def copyRandomList(self, head: Node | None) -> Node | None:
18-
new_dummy = Node(-1)
19-
old_dummy = Node(-1, next=head)
15+
old_to_new: dict[Node, Node] = {}
2016

21-
old_to_new: dict[Node | None, Node | None] = {None: None}
17+
dummy = Node(-1)
2218

23-
new_current = new_dummy
24-
old_current = old_dummy
19+
old = head
20+
new = dummy
2521

26-
while old_current.next:
27-
old_current = old_current.next
28-
new_node = Node(old_current.val)
29-
new_current.next = new_node
30-
new_current = new_current.next
22+
while old:
23+
node = Node(old.val, random=old.random)
24+
new.next = node
25+
new = node
3126

32-
old_to_new[old_current] = new_current
27+
old_to_new[old] = node
28+
old = old.next
3329

34-
new_current = new_dummy
35-
old_current = old_dummy
30+
current = dummy.next
3631

37-
while old_current.next and new_current.next:
38-
old_current = old_current.next
39-
new_current = new_current.next
40-
new_current.random = old_to_new[old_current.random]
32+
while current:
33+
if current.random:
34+
current.random = old_to_new[current.random]
35+
current = current.next
4136

42-
return new_dummy.next
37+
return dummy.next

0 commit comments

Comments
 (0)