gpt4 book ai didi

java - 递归地添加节点项。链表

转载 作者:行者123 更新时间:2023-12-02 03:41:58 26 4
gpt4 key购买 nike

所以我正在学习处理链表。我将如何递归地添加节点内的项目。我可以通过执行 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;
}
}

最佳答案

看起来您的代码不会添加最后一个节点。即使 h.nextnull,您也必须将 h.item 添加到总和中。

尝试:

static int addAll(node h) {
int sum = h.item;
if (h.next != null) {
sum += addAll(h.next);
}
return sum;
}

关于java - 递归地添加节点项。链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36737387/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com