I have a Java class, Node as follows :
class Node
{
public ArrayList<Node> nbrs;
}
Each Node object contains a list of all its neighbours within the ArrayList nbrs, and nothing else.
Now I need to write a function :
public Node copy( Node curr )
This function should perform a deep copy of the entire graph rooted at curr, and return the equivalent copy for curr.
I tried implementing a copy constructor within the class Node as follows :
public Node( Node n )
{
for( Node curr : n.nbrs )
n.nbrs.add( new Node( curr ));
}
I now copy the Node n, within my copy function.
But I have found that when the graph contains loops, this code keeps running infinitely.
Any help on how I should overcome this problem.
PS : This is an interview question faced by my friend, so the class Node cannot contain any more variables
The standard trick is to first create all the new nodes and store them in a map (from old nodes to new nodes). Then in a second pass over all the nodes, all the edges are added (by adding to
n.nbrs.add).