Skip to content

Commit

Permalink
re-solve "138. Copy List with Random Pointer"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Oct 27, 2024
1 parent 447d34c commit e0947f1
Showing 1 changed file with 17 additions and 22 deletions.
39 changes: 17 additions & 22 deletions src/copy_list_with_random_pointer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit e0947f1

Please sign in to comment.