java - Java中使用递归分离ArrayList的偶数和奇数索引

标签 java recursion arraylist

我试图将偶数和奇数索引与 java 中的 ArrayList 分开,作为作业的一部分。一定是递归方法。这是我尝试过的;;

public ArrayList<Integer> toOddList(ArrayList<Integer> input) {
        ArrayList<Integer> copiedList = (ArrayList<Integer>) input.clone();
        ArrayList<Integer> oddList = new ArrayList<Integer>();
        ArrayList<Integer> evenList = new ArrayList<Integer>();
        int index = (copiedList.size() - 1);      // Sets index to the max size of ArrayList - 1
        if (index <= 0) {
            return oddList;
        }
        if ((index % 2) == 0) {
            evenList.add(copiedList.get(index));  // Adds indexed number to even Arraylist
            copiedList.remove(index);             // Removes index from copiedList
            copiedList = toOddList(copiedList);   // Calls function again
        } else {
            oddList.add(copiedList.get(index));   // Adds indexed number to odd Arraylist
            copiedList.remove(index);             // Removes index from copied List
            copiedList = toOddList(copiedList);   // Call method again
        } return oddList;
    }

如果有任何其他方法可以为此使用递归,或者分别使用偶数和奇数两种方法,我们将不胜感激。

最佳答案

我借用了 Jarvis 使用索引而不是克隆输入数组的想法。我认为这里的目的是使我们已经到达列表末尾的基本情况,如果没有,我们将当前元素添加到正确的列表中,然后在列表的其余部分上调用自己,注意增加索引并切换当前列表和现有列表的位置。那么方法就变成了:

//assumes all lists initialized by caller
public void splitList(ArrayList<Integer> input, int index, ArrayList<Integer> current, ArrayList<Integer> onDeck) {
    if (index >= input.size()) { //base case
        return;
    } else { //add the current element and call us on the rest of the list
        current.add(input.get(index));
        splitList(input, index + 1, onDeck, current); //note toggling output list and advancing index
    }
}

一旦输入列表初始化并且奇数和偶数包含新构造的空数组列表,它就会被调用,如下所示:

splitList(splitThis, 0, evens, odds);//start with evens because 0 is even

修订: 我注意到可以不必过多担心索引,并且将“列表的其余部分”设为子列表会更自然。我还概括了任何类型的列表。因此:

//assumes all lists initialized by caller
public void splitList(List<Integer> input, List<Integer> current, List<Integer> onDeck) {
    if (input.size() == 0) { //base case
        return;
    } else { //add the current element and call us on the rest of the list
        current.add(input.get(0));
        splitList(input.subList(1, input.size()), onDeck, current); //note toggling output list and call on rest of list, if any
    }
}

并且调用被简化为:

splitList(splitThis, evens, odds);//start with evens because 0 is even

关于java - Java中使用递归分离ArrayList的偶数和奇数索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60255537/

相关文章:

java - Android推送通知: Multiple notifications displays same data

java - Android 致命信号 11

c - 双递归函数后使用顺序索引扫描数组

java - 创建不同对象的实例列表

java - 数组的 Arrays.asList()

java - ArrayList 的后备数组的长度与 ArrayList 的 .size() 不同

java - Java 中的数独板生成逻辑

java - 如何使用正则表达式来匹配多行与不情愿

c# - 如何进行递归 LINQ 查询?

algorithm - 给定一个树结构,你如何使用递归将它变成一个简单的链表?