Copy List with Random Pointer

A linked list contains nodes each with a random pointer that could point to any node in the list or null. Create a deep copy of this linked list. The copy should consist of new nodes with the same values as the original nodes, and the pointers in the new list should replicate the original list's structure without pointing to any nodes in the original list.

Constraints

  • 0 <= n <= 1000
  • -10^4 <= Node.val <= 10^4
  • Node.random is null or is pointing to some node in the linked list.
Saving… · 9 lines
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next

class Solution:
def copyListWithRandomPointer(self, head: 'ListNode') -> 'ListNode':

Console

Click Run to execute sample tests.