【问题标题】:Adding item of nodes, recursively. Linked list递归地添加节点项。链表
【发布时间】: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


【解决方案1】:

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

试试:

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

【讨论】:

    猜你喜欢
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 2019-02-26
    • 2013-06-20
    • 2017-03-19
    • 1970-01-01
    相关资源
    最近更新 更多