【问题标题】:Solve Java ArrayList remove with recursion index?使用递归索引解决 Java ArrayList 删除?
【发布时间】: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


    【解决方案1】:

    这是删除或删除的经典问题。

    您必须向后遍历列表。这样,当您删除一个元素时,您不会跳过其他元素或超出列表的末尾。

    public boolean Fire()
    {
        if (under.isEmpty())
            return true;
        else
        {
            for (int x = under.size() - 1; x >= 0; x--)
            {
                 if (under.get(x).Fire())
                     under.remove(x);
    
            }
    
        }
    
        return false;
    }
    

    【讨论】:

    • 我倾向于记住困扰我的问题。 :-)
    【解决方案2】:

    尝试使用迭代器。您只需在迭代器上使用.next() 继续遍历它,每当您发现某人没有他的员工时,您调用.remove()(在迭代器上)这将删除迭代器给您的最后一个元素。

    【讨论】:

      【解决方案3】:

      这就是为什么 Iterator 有 remove() 方法。查找 Collection 的 iterator() 调用并在你的 for 循环中使用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多