这是一个linked list, 其中的一个method是给每个值+上一个x, 我理解递归思路,但是我想知道不用递归,iterative 的方式如何写。
public class IntList {
public int first;
public IntList rest;
public IntList(int f, IntList r) {
first = f;
rest = r;
}
/** Return the size of the list using... recursion! */
public int size() {
if (rest == null) {
return 1;
}
return 1 + this.rest.size();
}
/** Return the size of the list using no recursion! */
public int iterativeSize() {
IntList p = this;
int totalSize = 0;
while (p != null) {
totalSize += 1;
p = p.rest;
}
return totalSize;
}
/** Returns the ith value in this list.*/
public int get(int i) {
}
/** Returns an IntList identical to L, but with
* each element incremented by x. L is not allowed
* to change. */
/**我想知道这个incrList method不用递归,如何用iterative 的方式写出来 */
public static IntList incrList(IntList L, int x) {
if (L == null) {
return L;
}
IntList incr = new IntList(L.first + x, incrList(L.rest, x));
return incr;
}
public static void main(String[] args) {
IntList L = new IntList(15, null);
L = new IntList(10, L);
L = new IntList(5, L);
System.out.println(L.iterativeSize());
}
}