Clone Linked List
Deep copy a linked list with next and random pointers
Code
1class Node:2 def __init__(self, val, next=None, random=None):3 self.val = val4 self.next = next5 self.random = random67def copyRandomList(head):8 if not head:9 return None1011 # Step 1: Create copy nodes and weave them in12 curr = head13 while curr:14 copy = Node(curr.val)15 copy.next = curr.next16 curr.next = copy17 curr = copy.next1819 # Step 2: Set random pointers for copies20 curr = head21 while curr:22 if curr.random:23 curr.next.random = curr.random.next24 curr = curr.next.next2526 # Step 3: Separate the two lists27 curr = head28 copy_head = head.next29 while curr:30 copy = curr.next31 curr.next = copy.next32 curr = copy.next33 if curr:34 copy.next = curr.next3536 return copy_head
Edge case
Linked List
INIT
Step
0 / 9
Phase
Initialize
Nodes
3
7
n:1
13
n:2r:0
11
Progress
Processing
Creating deep copy with next and random pointers...
Pointer State
Pointers
curr
0
copy
null
originalHead
0
copyHead
null
Key Insight
Weave copy nodes between originals, set randoms via curr.next.random = curr.random.next, then separate lists.
Explanation
INIT
Initialize
Clone list [7, 13, 11] with random pointers.
💡 Tip
O(n) approach: weave copy nodes in, set randoms, then separate.