【发布时间】:2016-04-20 07:58:37
【问题描述】:
所以我正在学习处理链表。我将如何递归地添加节点内的项目。我可以通过sum = h.item +h.next.item+h.next.next.item 来添加它们,但这只有在我有小的链表时才有效。下面是我的函数 addAll 尝试失败。
public class nodeP {
public static void main(String[] args) {
node H = new node(9);
H.next = new node(7);
H.next.next = new node(5);
System.out.println(addAll(H));
}
static int addAll(node h) {
int sum = 0;
if(h.next!=null) {
sum += h.item + addAll(h.next);
}
return sum;
}
}
【问题讨论】:
-
请注意,如果您有很多数字,您应该考虑使用 while 循环,以避免有太多的递归调用。
标签: java recursion data-structures nodes