CSC300: Backward recursion, non-nullable argument [6/11] Previous pageContentsNext page

11
12
13
14
15
16
17
18
19
  public int numFives () {
    if (first == null) return 0;
    return numFivesH (first);
  }
  private static int numFivesH (Node x) {
    int result = (x.next == null) ? 0 : numFivesH (x.next);
    if (x.item == 5) result = result + 1;
    return result;
  }
call@3 ([5,11,5,5])
  call@4 ([11,5,5])
    call@5  ([5,5])
      call@6  ([5])
      retn@6  ([5]) : 1
    retn@5  ([5,5]) : 2
  retn@4 ([11,5,5]) : 2
retn@3 ([5,11,5,5]) : 3

A more verbose version:

01
02
03
04
05
06
07
08
09
10
11
12
  public int numFives () {
    if (first == null) return 0;
    return numFivesH (first);
  }
  private static int numFivesH (Node x) {
    int result = 0;
    if (x.next != null) {
      result = numFivesH (x.next);
    }
    if (x.item == 5) result = result + 1;
    return result;
  }

Previous pageContentsNext page