Copying a cycle without endless recursion

Two mutable nodes form the cycle shown: A's next identifies B, and B's next identifies A. Each node also has primitive data fields. You need a deep copy that preserves this cycle without sharing either original node.


A recursive helper uses one shared lookup table keyed by original object identity. The table starts empty and records each original node together with its copied counterpart. Every helper call receives a non-null source node. Arrange the helper's steps in their correct execution order; a stated early return ends that call.


Two nodes form a cycle because each node's next reference identifies the other node.


  1. 1.

    Allocate a new destination node, copy the primitive data fields and leave its next reference unset.

  2. 2.

    Check the table for the source node; return its recorded counterpart if present, otherwise continue.

  3. 3.

    Return the destination node whose next field has now been assigned.

  4. 4.

    Record the source node and its new destination counterpart in the shared table.

  5. 5.

    Call the helper on the source's next node and assign the returned object to the destination's next field.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Shallow vs Deep Copies Questions: