CSC300: Linked structures: Cautious loop [4/17] Previous pageContentsNext page

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

For [5,11,5,5], the loop values (lines 5 and 9) are

x==[5,11,5,5], result==0
  x==[11,5,5], result==1
     x==[5,5], result==1
       x==[5], result==2
        x==[], result==3

Previous pageContentsNext page