java遍历链表元素_java-如何从链表中递归删除所有第三个元素...

如果您递归执行,则无需进行迭代.将问题简化为一次迭代,然后将其应用于当前状态,然后应用于列表的其余部分.似乎没有节点类,因此必须使用索引来完成.

删除第三个元素意味着保留当前的两个元素,然后删除后面的一个元素.我们还必须考虑到删除列表时该列表将“移动”,因此删除后不必前进.下一个“当前”将与我们从中删除的索引相同.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值