linkedlist

Deep clone random point singly list

December 16, 2023
medium
linkedlist

Problem # Given the head to a singly linked list, where each node also has a “random” pointer that points to anywhere in the linked list, deep clone the list. Solution 1 # class ListNode: def __init__(self, value=0, next=None, random=None): self.value = value self.next = next self.random = random def deep_clone(head): """ Deep clone a linked list where each node has a 'next' pointer and a 'random' pointer. :param head: Head node of the original linked list :return: Head node of the cloned linked list """ if not head: return None # Step 1: Create a new node for each node in the original list and insert it between the original node and its next node current = head while current: new_node = ListNode(current. ...