Weird copying linked list-ish thing with random
This commit is contained in:
@@ -509,3 +509,29 @@ def count_factorial_trailing_zeroes(number: int) -> int:
|
||||
divisor *= 5
|
||||
|
||||
return zeroes_count
|
||||
|
||||
|
||||
def copy_random_list(
|
||||
head: stdlib.ListNodeRandom | None,
|
||||
) -> stdlib.ListNodeRandom | None:
|
||||
if head is None:
|
||||
return None
|
||||
|
||||
ordered = []
|
||||
cur = head
|
||||
while cur is not None:
|
||||
ordered.append(cur)
|
||||
cur = cur.next
|
||||
|
||||
ordered_copy = [stdlib.ListNodeRandom(entry.val) for entry in ordered]
|
||||
|
||||
hash_idx = {hash(n): i for i, n in enumerate(ordered)}
|
||||
|
||||
for i, entry in enumerate(ordered):
|
||||
if i + 1 < len(ordered_copy):
|
||||
ordered_copy[i].next = ordered_copy[i + 1]
|
||||
|
||||
if entry.random is not None:
|
||||
ordered_copy[i].random = ordered_copy[hash_idx[hash(entry.random)]]
|
||||
|
||||
return ordered_copy[0]
|
||||
|
||||
Reference in New Issue
Block a user