如果您递归执行,则无需进行迭代.将问题简化为一次迭代,然后将其应用于当前状态,然后应用于列表的其余部分.似乎没有节点类,因此必须使用索引来完成.
删除第三个元素意味着保留当前的两个元素,然后删除后面的一个元素.我们还必须考虑到删除列表时该列表将“移动”,因此删除后不必前进.下一个“当前”将与我们从中删除的索引相同.
public void removeElements(List list, int current) {
int removeIndex = current + 2; // remove the third element
if (removeIndex >= list.size()) // if there isn't one, stop
return;
list.remove(removeIndex); // if there is one, remove it
removeElements(list, removeIndex); // continue with the rest of the list
}
为了避免总是需要准备该方法,您可以编写另一个为您准备的方法:
public void removeElements(List list) {
removeElements(list, 0);
}
例如:
List list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
list.add(8);
list.add(9);
list.add(10);
removeElements(list);
for (int x = 0; x < list.size(); x++)
System.out.println(list.get(x));
// output: 1 2 4 5 7 8 10
由于您更新了要删除的第n个项目,因此可以通过修改添加到当前索引的值来轻松更改:
public void removeElements(List list, int current, int n) {
int removeIndex = current + n - 1; // remove the nth element
if (removeIndex >= list.size()) // if there isn't one, stop
return;
list.remove(removeIndex); // if there is one, remove it
removeElements(list, removeIndex, n); // continue with the rest of the list
}
public void removeEverySecond(List list) {
removeElements(list, 0, 2);
}
public void removeEveryThird(List list) {
removeElements(list, 0, 3);
}
// etc.