开发者

How to recursively iterate through a recursive data structure

I have a datastructure as follows:

 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

and so on. Note: No B comes after B.

Now i want to iterate though the map of class B, i.e 开发者_JAVA百科AMap. I am trying to create an XML-structure out of it. I want some attribute like id-number. The id-number at each level for A and B should be like we have structure in books. What is the most efficient way to do this?


look at the problem as a bipartite-graph, and run a DFS.

EDIT: added code snap

I did not debug it, but it should be something like that [look at the iterate method]. Activate it with 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);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜