From e0947f14c6f420e5ae41d305e6b4dc4caf8e525d Mon Sep 17 00:00:00 2001 From: Pavel Karateev Date: Sun, 27 Oct 2024 13:08:20 +0100 Subject: [PATCH] re-solve "138. Copy List with Random Pointer" --- src/copy_list_with_random_pointer.py | 39 ++++++++++++---------------- 1 file changed, 17 insertions(+), 22 deletions(-) diff --git a/src/copy_list_with_random_pointer.py b/src/copy_list_with_random_pointer.py index d45d956..f90a77b 100644 --- a/src/copy_list_with_random_pointer.py +++ b/src/copy_list_with_random_pointer.py @@ -4,39 +4,34 @@ class Node: def __init__( self, x: int, next: Node | None = None, random: Node | None = None - ): + ) -> None: self.val = int(x) self.next = next self.random = random - def __str__(self) -> str: - return f"Node({self.val})" - class Solution: def copyRandomList(self, head: Node | None) -> Node | None: - new_dummy = Node(-1) - old_dummy = Node(-1, next=head) + old_to_new: dict[Node, Node] = {} - old_to_new: dict[Node | None, Node | None] = {None: None} + dummy = Node(-1) - new_current = new_dummy - old_current = old_dummy + old = head + new = dummy - while old_current.next: - old_current = old_current.next - new_node = Node(old_current.val) - new_current.next = new_node - new_current = new_current.next + while old: + node = Node(old.val, random=old.random) + new.next = node + new = node - old_to_new[old_current] = new_current + old_to_new[old] = node + old = old.next - new_current = new_dummy - old_current = old_dummy + current = dummy.next - while old_current.next and new_current.next: - old_current = old_current.next - new_current = new_current.next - new_current.random = old_to_new[old_current.random] + while current: + if current.random: + current.random = old_to_new[current.random] + current = current.next - return new_dummy.next + return dummy.next