CSC300: Get your loops straight! [2/10] Previous pageContentsNext page

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class LinkedList {
  class Node { double item; Node next; }
  Node first;
  
  public double numFives1 () {
    double result = 0;    
    Node current = first; // may be null
    while (current != null) {
      if (current.item == 5.0) result = result + 1;
      current = current.next;
    }
  }

  public double numFives2 () {
    if (first == null) return 0;
    double result = 0;
    if (first.item == 5.0) result = 1;
    Node prev = first; // never null
    while (prev.next != null) {
      if (prev.next.item == 5.0) result = result + 1;
      prev = prev.next;
    }
  }

  public double numFives3 () {
    if (first == null) return 0;
    double result = 0;
    if (first.item == 5.0) result = 1;
    Node prev = first;         // never null
    Node current = first.next; // may be null
    while (current != null) {
      if (current.item == 5.0) result = result + 1;
      prev = prev.next;
      current = current.next;
    }
  }
}

public static double numFives (double[] a) {
  double result = 0;
  int i = 0;
  while (i<a.length) {
      if (a[i] == 5.0) result = result + 1;
     i = i + 1;
  }
}

Previous pageContentsNext page