递归地添加节点项。链接列表

时间:2016-04-20 07:58:37

标签: java recursion data-structures nodes

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

1 个答案:

答案 0 :(得分:2)

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

尝试:

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