0
一個函數,它接受一個節點並複製該節點和所有相鄰節點以創建一個與此節點完全相似的新結構。複製圖形節點以創建節點網絡的全新複製
甲
/\
乙CE
\/
d
應該創建新節點
一個節點對象通過
節點{限定的類似網絡
Arraylist neighbors; //返回數組列表中的所有相鄰節點
}
此代碼是否工作?
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;
}
請建議我在這裏錯過什麼?