|
4 | 4 | class Node:
|
5 | 5 | def __init__(
|
6 | 6 | self, x: int, next: Node | None = None, random: Node | None = None
|
7 |
| - ): |
| 7 | + ) -> None: |
8 | 8 | self.val = int(x)
|
9 | 9 | self.next = next
|
10 | 10 | self.random = random
|
11 | 11 |
|
12 |
| - def __str__(self) -> str: |
13 |
| - return f"Node({self.val})" |
14 |
| - |
15 | 12 |
|
16 | 13 | class Solution:
|
17 | 14 | 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] = {} |
20 | 16 |
|
21 |
| - old_to_new: dict[Node | None, Node | None] = {None: None} |
| 17 | + dummy = Node(-1) |
22 | 18 |
|
23 |
| - new_current = new_dummy |
24 |
| - old_current = old_dummy |
| 19 | + old = head |
| 20 | + new = dummy |
25 | 21 |
|
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 |
31 | 26 |
|
32 |
| - old_to_new[old_current] = new_current |
| 27 | + old_to_new[old] = node |
| 28 | + old = old.next |
33 | 29 |
|
34 |
| - new_current = new_dummy |
35 |
| - old_current = old_dummy |
| 30 | + current = dummy.next |
36 | 31 |
|
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 |
41 | 36 |
|
42 |
| - return new_dummy.next |
| 37 | + return dummy.next |
0 commit comments