我的数据结构如下:
public class A{
String number;
Map <String ,B> BMap;
}
public class B{
String number;
Map <String ,A> AMap;
}
<小时/>
0 B
0.0 A
0.1 A
0.1.0 B
...so on
1 B
1.0 A
1.0.0 B
1.1 A
等等。 注意: B
之后没有 B
。
现在我想迭代B
类的映射,即AMap
。我正在尝试用它创建一个 XML 结构。我想要一些属性,例如 ID 号。 A
和 B
每个级别的 id-number 应该像我们书中的结构一样。最有效的方法是什么?
最佳答案
将问题视为 bipartite-graph ,然后运行 DFS .
编辑:添加代码快照
我没有调试它,但它应该是类似的东西[看看迭代方法]。使用 iterate(new HashSet<A>(),new HashSet<B>())
激活它
public class A{
String number;
Map<String ,B> BMap;
public void iterate(Set<A> aVisited,Set<B> bVisited) {
for (Entry<String, B> entry : BMap.entrySet()) {
if (bVisited.contains(entry.getValue())) continue;
System.out.println(entry.getKey());
bVisited.add(entry.getValue());
entry.getValue().iterate(aVisited,bVisited);
}
}
}
public class B{
String number;
Map<String ,A> AMap;
public void iterate(Set<A> aVisited,Set<B> bVisited) {
for (Entry<String, A> entry : AMap.entrySet()) {
if (aVisited.contains(entry.getValue())) continue;
System.out.println(entry.getKey());
aVisited.add(entry.getValue());
entry.getValue().iterate(aVisited,bVisited);
}
}
}
关于java - 如何递归地迭代递归数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7227707/