一个函数,它接受一个节点,并复制该节点和所有相邻节点,以创建一个与此结构完全相似的新结构。
A
/\
B C-E
\/
D
应使用新节点创建类似的网络
Node对象由定义
节点{
Arraylist neighbours;//返回数组列表中的所有相邻节点
}
这段代码能工作吗?
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;
}请建议我这里遗漏了什么?
发布于 2012-07-14 17:46:01
此代码将以抛出堆栈溢出异常结束。
问题:
解决方案:
其他潜在问题:
https://stackoverflow.com/questions/11480412
复制相似问题