VOOZH about

URL: https://www.geeksforgeeks.org/dsa/a-linked-list-with-next-and-arbit-pointer/

⇱ Clone a Linked List with Random Pointer - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Clone a Linked List with Random Pointer

Last Updated : 4 Apr, 2026

Given a head of linked list where each node has two links: next pointer pointing to the next node and random pointer to any random node in the list. Create a clone of this linked list.

👁 file

[Naive Approach] Using Hashing - O(n) Time and O(n) Space

The idea is to create a new node for each original node, store them in a hash table, then update the next and random pointers of the new nodes.

  • Create a hash table mp to map original nodes to new nodes.
  • Traverse the original list and for each node curr, create a new node and store it in the hash table mp[curr] = new Node().
  • Traverse the list again to update the next and random pointers of the new nodes: mp[curr]->next = mp[curr->next] and mp[curr]->random = mp[curr->random].
  • Return mp[head] as the head of the cloned linked list.



Output
Original linked list:
1(3) -> 2(1) -> 3(5) -> 4(3) -> 5(2)
Cloned linked list:
1(3) -> 2(1) -> 3(5) -> 4(3) -> 5(2)

[Expected Approach] By Inserting Nodes In-place - O(n) Time and O(1) Space

The idea is to create duplicate of a node and instead of storing in a separate hash table, we can insert it in between the original node and the next node. Now, we will have new nodes at alternate positions.

  • Traverse the list and insert a cloned node after each original node. For every node X, create X', place it as X -> X' -> next.
  • Traverse again and update the random pointers of cloned nodes. X'->random = X->random->next (if random exists).
  • Traverse the list again to separate the two lists. Restore original links and extract cloned links.
  • Fix pointers: original->next = original->next->next, clone->next = clone->next->next.
  • Return the head of the cloned list.



Output
Original linked list:
1(3) -> 2(1) -> 3(5) -> 4(3) -> 5(2)
Cloned linked list:
1(3) -> 2(1) -> 3(5) -> 4(3) -> 5(2)
Comment