我正在使用 Java 中的一个简单的
IntList
类。
public class IntList {
public int first;
public IntList rest;
public IntList(int f, IntList r) {
first = f;
rest = r;
}
对于给定的
IntList
,我需要一个方法incrList
,它将把L
的所有成员增加x
,同时不修改L
。这是我的解决方案:
public static IntList incrList(IntList L, int x) {
IntList newList;
if (L.rest == null) {
newList = new IntList(L.first + x, null);
} else {
newList = new IntList(L.first + x, incrList(L.rest, x));
}
return newList;
}
我已经意识到这可以在没有
new
关键字的情况下完成,但我什至不知道在不创建新对象的情况下从哪里开始。
first = head
rest = tail
public static IntList dincrList(IntList L, int x) {
/** Using recursion, but iteration also works. */
if (L == null) {
return null;
}
L.head = L.head + x;
/* Don't actually care about the return value here. */
dincrList(L.tail, x);
return L;
}