lluvia900125 2023-01-18 15:11 采纳率: 45%

# java链表递归的另一种实现方法

``````
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;
}
}

/** 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());
}
}

``````
• 写回答

#### 5条回答默认 最新

• 游一游走一走 2023-01-18 15:30
关注
``````
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;
}
}

/**
* 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 IntList incrList2(IntList L, int x) {
if (L == null) {
return L;
}
IntList temp = L;
IntList incr = new IntList(temp.first + x, null);
IntList temp2 = incr;
while (temp.rest != null) {
temp = temp.rest;
temp2.rest = new IntList(temp.first + x, null);
temp2 = temp2.rest;
}
return incr;
}

@Override
public String toString() {
return "IntList{" +
"first=" + first +
", rest=" + rest +
'}';
}

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);
System.out.println(IntList.incrList2(L, 1));
}
}

``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论 编辑记录

• 系统已结题 1月26日
• 已采纳回答 1月18日
• 创建了问题 1月18日

#### 悬赏问题

• ¥15 MATLAB动图问题
• ¥15 有段代码不知道怎么理解，const isToken = (config.headers || {}).isToken === false
• ¥100 采用栈和深度优先算法对我的代码进行修改显示路径
• ¥15 pointnet2包安装
• ¥20 射频功率问题，解答者有酬谢！
• ¥80 构建降雨和积水的预测模型
• ¥15 #Qt Transform setTransform()在鼠标拖动移动视角是一致在原地不动，无法变换视角（细微观察似乎视图有在原地抖动），无法变换视角（细微观察似乎视图有在原地抖动）
• ¥50 如何利用无人机拍摄的数码照片测量鸟卵的长短径
• ¥100 github贡献者给与奖励
• ¥15 使用DS18B20+ESP8266获取温度数据返回-127.00