【发布时间】:2013-05-03 16:58:30
【问题描述】:
我有一个奇怪的问题,我知道如何解决,但这次我想用数组列表来解决。这是问题所在: 我有一棵员工树。 Employee 是一个简单的类(下面是为该员工工作的员工列表):
class Employee
{
String name;
ArrayList<Employee> under = new ArrayList<Employee>();
//fire function
}
我的任务是递归解雇所有没有员工的员工。我知道如何使用定制的列表数据结构来解决这个问题,但我想用数组列表来做。到目前为止,这是我的代码:
public boolean Fire()
{
if (under.isEmpty())
return true;
else
{
for (int x = 0; x < under.size(); x ++)
{
if (under.get(x).Fire())
under.remove(x);
}
}
return false;
}
但这段代码的问题是,当我删除 under.remove(x) 时,under.size() 会变小并且索引会变得混乱。我尝试在每个 under.remove(x) 之后设置 x = 0,但它并没有完全正确。一名员工还剩下很多。有数组列表结构的解决方案吗?
【问题讨论】:
标签: java algorithm recursion arraylist