Foo
needs a print
method that prints its contents and then calls the print
method of the Foo
it's pointing to. Print
takes a HashSet that contains all Foo
objects that have been traversed. If next
is in visited
then it's part of a cycle and you don't call its print
method.
class Foo {
Foo next;
void print(HashSet<Foo> visited) {
System.out.println("this Foo's ID or whatever it is you're printing");
visited.add(this);
if(next != null && !visited.contains(next)) {
next.print(visited);
}
}
}
You may also want to pass in an int
parameter that determines the level of indentation - if indent
equals 4 then print 4 spaces before the System.out.println
, and increment indent
by 2 or 4 or whatever when you call print
on next
.