0

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;
   }
}
1
  • 1
    note that if you have many numbers, you should consider using a while loop instead, to avoid having too many recursing calls. Commented Apr 20, 2016 at 8:10

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.