HPotter
HPotter

Reputation: 141

Adding item of nodes, recursively. Linked list

So I am learning about processing linked list. How would I add the items inside the nodes recursively. I could add them by doing sum = h.item +h.next.item+h.next.next.item, but that would only work if i had small linked list. Below is my function addAll with failed attempt.

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

Upvotes: 0

Views: 76

Answers (1)

Eran
Eran

Reputation: 393801

It looks like your code will not add the last node. You have to add h.item to the sum even when h.next is null.

Try :

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

Upvotes: 2

Related Questions