C# How can detect cyclic references? -
for 1 given instance of treelist, how can check whether or not instance of treelist, added first treelist, contains (possibly indirect) reference first treelist (which create cyclic reference)?
for example:
treelist t1 = new treelist(); treelist t2 = new treelist(); treelist t3 = new treelist(); t1.add(t2); t2.add(t3); t3.add(t1);
because when iterrate through stuck in loop, because after t3 t1. how can check if 1 included in order.
class treelist { public string name { get; set; } list<treelist> items = new list<treelist>(); public readonlycollection<treelist> items { { return items.asreadonly(); } } public treelist(string name) { this.name = name; } public void add(string item) { items.add(new treelist(item)); } public void add(treelist subtree) { items.add(subtree); } public override string tostring() { return name; } }
i think these methods work:
public bool containsrecursively(treelist node) { foreach (treelist child in items) if (child == node || child.containsrecursively(node)) return true; return false; } public void add(treelist tree) { if (this == tree) return; // tree 'tree', don't add ourselves! if (this.containsrecursively(tree)) return; // 'tree' in tree if (tree.containsrecursively(this)) return; // tree in 'tree' items.add(tree); }
Comments
Post a Comment