|
|
|
|
|
|
l******e 发帖数: 42 | 1 /* There exists the following interface
public interface Container {
Container getParent(); //if there is no parent, getParent() returns null
String getName();
}
Create a method printContainers(Container c) that prints out the names of
all the parent containers in the order of the top-most parent container
first.
For example, assume the following:
a.getParent() returns b
a.getName() returns "foo"
b.getParent() returns null
b.getName() returns "bar"
printContainers(a) should print to the console:
"bar"
"foo"
*/ | l******e 发帖数: 42 | 2 I figured something like this may work. Please point out anything you see to
correct or improve. thanks!
/////this is a recursive function question
static void printContainer ( Container c)
{
public Stack nameStack = new Stack();
parent1st(c);
while (!nameStack.empty()) {
system.out.println (NameStack.pop());
}
}
static void parent1st(Container c)
{
nameStack.push(c.getName());
if (c.getParent() == null)
return;
else
parent1st((c.getParent());
} |
|
|
|
|
|