Given a list of integers a, return a new list which contains all the positive elements of
a
using recursion. The elements should appear in the result in the same relative order as ina
. i.e.[2, 3, -5, 8, -2] ==> [2, 3, 8]
.
public static List positives(List a) {
if (a.isEmpty())
return List.empty();
if (a.getHead() > 0)
return positives(a.getTail());
else
return List.cons(0, a);
}
最佳答案
您还没有发布 List
的代码,但算法应该是这样的:
- 如果列表为空,则返回空列表 (
List.empty()
)。 - 如果头元素为正 (
a.getHead() > 0
),则保留它并返回该元素和尾部正元素的列表(使用List.cons
)。 - 如果头元素为负,则删除它并仅返回尾部的正元素列表。
在您当前的代码中,第一点正确完成,但其他两点不正确:在 head 元素为正的情况下,您将忽略它(如果 head 元素为负,则您应该这样做)。
这应该足以让您更正代码。
关于java - 给定一个整数 a 列表,使用递归返回一个新列表,其中包含 a 的所有正元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34843083/