CSC300: Linked List Accessors

Contents [0/11]

Video [1/11]
Starter code [2/11]
Loop [3/11]
Forward recursion, nullable argument [4/11]
Forward recursion, non-nullable argument [5/11]
Backward recursion, non-nullable argument [6/11]
Backward recursion, nullable argument [7/11]
Starter code with both array and linked list [8/11]
Another Problem [9/11]
Loop using current [10/11]
Loop using previous [11/11]

(Click here for one slide per page)


Video [1/11]

In three parts.

Only the first and third videos will be covered on exams. The second video is a preview of material that is covered in CSC 301/403.

Open Playlist

00:00 A Playground for Linked Lists
02:20 Why is Node a static class
03:57 How a list is created
08:52 How to access a specific item
10:08 Visualizing a pointer to a specific item
11:59 Writing a loop: The middle
14:27 Writing a loop: The end
15:07 Writing a loop: The beginning
15:57 Visualizing the execution of the loop

Open Playlist

00:00 Forward recursion with nullable parameter
03:51 Thinking about loops and recursion
06:41 Forward recursion with non-nullable parameter
10:04 Backward recursion with non-nullable parameter
13:33 Backward recursion with nullable parameter

Open Playlist

00:00 Using a current pointer
05:30 Using a previous pointer

Starter code [2/11]

file:Playground.java [source] [doc-public] [doc-private]
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package algs13;
import java.text.DecimalFormat;
import stdlib.*;
public class Playground {
  private Node first;
  static class Node { 
    public double item; 
    public Node next; 
    public Node (double item, Node next) { 
      this.item = item; 
      this.next = next; 
    }
  }

  public int numFives () {
    return StdRandom.uniform (100); //TODO: fix this
  }

  public static void main1 (String[] args) {
    Trace.showBuiltInObjects(true);
    Trace.drawStepsOfMethod ("numFives");
    Trace.drawStepsOfMethod ("numFivesH");
    Trace.run ();
    Playground list1 = Playground.of ("5 11 5 5");
    Playground list2 = Playground.of ("24 35 67");
    int result1 = list1.numFives ();
    Trace.draw();
    StdOut.println ("result: " + result1);
  }

  public static void main2 (String[] args) {
    Trace.showBuiltInObjects(true);
    Trace.drawStepsOfMethod ("main");
    Trace.drawStepsOfMethod ("example");
    //Trace.drawSteps();
    Trace.run ();
    Playground example1 = Playground.example (1);
    Playground example2 = Playground.example (5);
    Playground example3 = Playground.example (7);
    Node x = example1.first;
    StdOut.println (x.item);
  }

  /* A silly method to show list creation */
  public static Playground example(int i) {
    Node x1 = new Node (i+10, null);
    Node x2 = new Node (i+20, null);
    Node x3 = new Node (i+30, null);
    Node x4 = new Node (i+40, null);
    Playground result = new Playground ();
    result.first = x1;
    x1.next = x2;
    x2.next = x3;
    x3.next = x4;
    return result;
  }


  public static void main (String[] args) {
    testNumFives (2, "11 5 5 21");
    testNumFives (0, "11 21 31 41");
    testNumFives (1, "11 21 5 31 41");
    testNumFives (1, "5 11 21 31 41");
    testNumFives (1, "11 21 31 41 5");
    testNumFives (5, "5 11 21 5 5 31 5 41 5");
    testNumFives (3, "5 5 5");
    testNumFives (1, "5");
    testNumFives (0, "11");
    testNumFives (0, "");
    StdOut.println ("Finished tests");
  }

  private static void testNumFives (int expected, String sList) {
    Playground list = Playground.of (sList); 
    String sStart = list.toString ();
    int actual = list.numFives ();
    if (expected != actual) {
      StdOut.format ("Failed: Expecting [%d] Actual [%d] with argument %s\n", expected, actual, list);
    }
    String sEnd = list.toString ();
    if (! sStart.equals (sEnd)) {
      StdOut.format ("Failed %s.numFives(): List changed to %s\n", sStart, sEnd);
    }
  }

  /* ToString method to print */
  public String toString () { 
    // Use DecimalFormat #.### rather than String.format 0.3f to leave off trailing zeroes
    DecimalFormat format = new DecimalFormat ("#.###");
    StringBuilder result = new StringBuilder ("[ ");
    for (Node x = first; x != null; x = x.next) {
      result.append (format.format (x.item));
      result.append (" ");
    }
    result.append ("]");
    return result.toString ();
  }

  /* Method to create lists */
  public static Playground of(String s) {
    Playground result = new Playground ();
    if ("".equals (s)) return result;

    Node first = null;
    String[] nums = s.split (" ");
    for (int i = nums.length-1; i >= 0; i--) {
      try { 
        double num = Double.parseDouble (nums[i]); 
        first = new Node (num, first);      
      } catch (NumberFormatException e) {
        throw new IllegalArgumentException (String.format ("Bad argument \"%s\": could not parse \"%s\" as a double", s, nums[i]));
      }
    }
    result.first = first;
    return result;
  }

}

Loop [3/11]

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

For [5,11,5,5], the loop values (line 4) 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 (x==null)

There is an image to the right of the code.
Click to animate in single-slide mode.
To enter single-slide mode, click the slide number in the title bar.

numFivesLIO-

Forward recursion, nullable argument [4/11]

11
12
13
14
15
16
17
18
19
  public int numFives () {
    return numFivesH (first, 0);
  }
  private static int numFivesH (Node x, int result) {
    if (x == null) return result;
    if (x.item == 5) result = result + 1;
    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)
        call@7 ([], 3)
        retn@7 ([], 3) : 3
      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
numFivesLROF-

Forward recursion, non-nullable argument [5/11]

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
numFivesLRCF-

Backward recursion, non-nullable argument [6/11]

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;
  }
numFivesLRCB-

Backward recursion, nullable argument [7/11]

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

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

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

Starter code with both array and linked list [8/11]

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package algs13;
import java.text.DecimalFormat;
import stdlib.*;
public class Playground {
  private double a[]; 
  private Node first;
  static class Node { 
    public double item; 
    public Node next; 
    public Node (double item, Node next) { 
      this.item = item; 
      this.next = next; 
    }
  }

  public int numFives () {
    return StdRandom.uniform (100); //TODO: fix this
  }

  /* ToString method to print */
  public String toString () { 
    // Use DecimalFormat #.### rather than String.format 0.3f to leave off trailing zeroes
    DecimalFormat format = new DecimalFormat ("#.###");
    StringBuilder result = new StringBuilder ("[ ");
    for (Node x = first; x != null; x = x.next) {
      result.append (format.format (x.item));
      result.append (" ");
    }
    result.append ("]");
    return result.toString ();
  }

  /* Method to create lists */
  public static Playground of(String s) {
    Playground result = new Playground ();
    if ("".equals (s)) {
      // special case for the empty array
      result.first = null;
      result.a = new double [0];
    } else {
      String[] nums = s.split (" ");
      Node first = null;
      double[] a = new double[nums.length];
      for (int i = nums.length-1; i >= 0; i--) {
        double num = Double.NaN;
        try { 
          num = Double.parseDouble (nums[i]); 
        } catch (NumberFormatException e) { 
          throw new IllegalArgumentException (String.format ("Bad argument \"%s\": could not parse \"nums[i]\" as a double", s, nums[i]));
        }
        a[i] = num;
        first = new Node (num, first);  
      }
      result.a = a;
      result.first = first;
    } 
    return result;
  }

  public static void testNumFives (int expected, String sList) {
    Playground list = Playground.of (sList); 
    int actual = list.numFives ();
    if (expected != actual) {
      StdOut.format ("Failed: Expecting [%d] Actual [%d] with argument %s\n", expected, actual, list);
    }
  }
  public static void main (String[] args) {
    testNumFives (0, "");
    testNumFives (1, "5");
    testNumFives (0, "11");
    testNumFives (3, "5 5 5");
    testNumFives (0, "11 21 31 41");
    testNumFives (1, "5 11 21 31 41");
    testNumFives (1, "11 21 31 41 5");
    testNumFives (1, "11 21 5 31 41");
    testNumFives (5, "5 11 21 5 5 31 5 41 5");
    StdOut.println ("Finished tests");
  }
  public static void main1 (String[] args) {
    Trace.drawStepsOfMethod ("numFives");
    Trace.drawStepsOfMethod ("numFivesH");
    Trace.run ();
    Playground list0 = Playground.of ("5");
    Playground list1 = Playground.of ("5 11 5 5");
    int result = list1.numFives ();
    StdOut.println ("result: " + result);
  }
}

Another Problem [9/11]

file:PlaygroundNumUnique.java [source] [doc-public] [doc-private]
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package algs13;
import java.text.DecimalFormat;
import stdlib.*;
public class PlaygroundNumUnique {
  private Node first;
  static class Node { 
    public double item; 
    public Node next; 
    public Node (double item, Node next) { 
      this.item = item; 
      this.next = next; 
    }
  }
  
  /** Number of unique items, assuming the list is sorted */
  public int numUnique() {
    return StdRandom.uniform (100); //TODO: fix this
  }

  public static void main1 (String[] args) {
    Trace.showBuiltInObjects(true);
    Trace.drawStepsOfMethod ("numUnique");
    Trace.run ();
    PlaygroundNumUnique list1 = PlaygroundNumUnique.of ("11 21 21 21 31");
    int result1 = list1.numUnique ();
    Trace.draw();
    StdOut.println ("result: " + result1);
  }

  public static void main (String[] args) {
    testNumUnique(4, "11 21 21 21 31 41 41 41 41");
    testNumUnique(1, "11 11 11 11");
    testNumUnique(4, "11 21 31 41");
    testNumUnique(4, "11 11 11 21 31 31 31 31 41");
    testNumUnique(4, "11 11 21 21 21 31 31 41 41 41 41");
    testNumUnique(8, "11 11 11 11 21 31 41 41 41 41 41 51 51 61 71 81 81");
    testNumUnique(8, "11 21 31 41 41 41 41 41 51 51 61 71 81");
    testNumUnique(7, "11 11 11 11 21 31 41 41 41 41 41 51 51 61 71");
    testNumUnique(7, "11 21 31 41 41 41 41 41 51 51 61 71");
    testNumUnique(8, "-81 -81 -81 -81 -71 -61 -51 -51 -51 -51 -41 -41 -31 -21 -11 -11 -11");
    testNumUnique(3, "-11 -11 -11 0 0 11 11 11");
    testNumUnique(2, "0 11 11 11");
    testNumUnique(2, "-Infinity 11 11 11");
    testNumUnique(2, "11 11 11 Infinity");
    testNumUnique(1, "11 11");
    testNumUnique(1, "11");
    testNumUnique(0, "");
    
    StdOut.println ("Finished tests");
  }

  private static void testNumUnique (int expected, String sList) {
    PlaygroundNumUnique list = PlaygroundNumUnique.of (sList); 
    String sStart = list.toString ();
    int actual = list.numUnique ();
    if (expected != actual) {
      StdOut.format ("Failed: Expecting [%d] Actual [%d] with argument %s\n", expected, actual, list);
    }
    String sEnd = list.toString ();
    if (! sStart.equals (sEnd)) {
      StdOut.format ("Failed %s.numUnique(): List changed to %s\n", sStart, sEnd);
    }
  }

  /* ToString method to print */
  public String toString () { 
    // Use DecimalFormat #.### rather than String.format 0.3f to leave off trailing zeroes
    DecimalFormat format = new DecimalFormat ("#.###");
    StringBuilder result = new StringBuilder ("[ ");
    for (Node x = first; x != null; x = x.next) {
      result.append (format.format (x.item));
      result.append (" ");
    }
    result.append ("]");
    return result.toString ();
  }

  /* Method to create lists */
  public static PlaygroundNumUnique of(String s) {
    PlaygroundNumUnique result = new PlaygroundNumUnique ();
    if ("".equals (s)) return result;

    Node first = null;
    String[] nums = s.split (" ");
    for (int i = nums.length-1; i >= 0; i--) {
      try { 
        double num = Double.parseDouble (nums[i]); 
        first = new Node (num, first);      
      } catch (NumberFormatException e) {
        throw new IllegalArgumentException (String.format ("Bad argument \"%s\": could not parse \"%s\" as a double", s, nums[i]));
      }
    }
    result.first = first;
    return result;
  }
}

Loop using current [10/11]

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  public int numUnique() {
    if (first == null) return 0;
    int result = 1;
    Node curr = first.next;
    double prevVal = first.item;
    while (curr != null) {

      double currVal = curr.item;
      if (currVal != prevVal) {
        result += 1;
        prevVal = currVal;
      }
      curr = curr.next;
    }
    return result;
  }
NumUniqueCurr-

Loop using previous [11/11]

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  public int numUnique() {
    if (first == null) return 0;
    int result = 1;
    
    Node prev = first;
    while (prev.next != null) {     
      double prevVal = prev.item;
      double currVal = prev.next.item;
      if (currVal != prevVal) {
        result += 1;

      }
      prev = prev.next;
    }
    return result;
  }
NumUniquePrev-

Revised: 2008/03/17 13:01