CSC300: Linked structures: Cautious, forward recursion [7/17] Previous pageContentsNext page

11
12
13
14
15
16
17
18
19
  public int numFives () {
    if (first == null) return 0;
    return numFivesH (first, 0);
  }
  private static int numFivesH (Node x, int result) {
    if (x.item == 5) result = result + 1;
    if (x.next != null) result = numFivesH (x.next, result);
    return result;
  }

For [5,11,5,5], the call tree is

call@3 ([5,11,5,5], 0)
  call@4 ([11,5,5], 1)
    call@5  ([5,5], 1)
      call@6  ([5], 2)
      retn@6  ([5], 2) : 3
    retn@5  ([5,5], 1) : 3
  retn@4 ([11,5,5], 1) : 3
retn@3 ([5,11,5,5], 0) : 3

Previous pageContentsNext page