Reputation: 51
A function that takes a node and copies this and all the adjacent node to create a new structure exactly similar to this one.
A
/ \
B C-E
\ /
D
should create similar network with new nodes
A Node object is defined by
Node{
Arraylist neighbours; // returns all the adjacent nodes in an array list
}
Will this code work?
public Node copyGraph(Node A){
HashTable<Node, Node> hash = new HashTable<Node, Node> ();
return copyGraphWithHash(A, hash);
}
public Node copyGraphWithHash(Node A, HashTable<Node, Node> hash){
if (A.neighbours.size() == 0)
return null;
Node newfirst = null;
if(!hash.hasKey(A))
newfirst = new Node();
hash.add(A,newfirst);
}
for ( Node n : A.neighbours()){
if (copyGraphWithHash(n, hash))
newfirst.neightbours.add(copyGraphWithHash(n, hash));
}
return newfirst;
}
Please suggest what am I missing here ?
Upvotes: 0
Views: 288
Reputation: 2191
This code will end by throwing a stack overflow exception.
Problems :
Solutions :
Other potential problems :
Upvotes: 1