CS 2 (Winter 2024) Lab 03: Memory

This lab focuses on the memory model, references, linked lists, and recursion.

Setup

Register for the lab using grinch: https://grinch.caltech.edu/register and clone the repository as explained in the setup instructions.

Part 0

Trace through each of the following lines of code carefully to determine what memory looks like after each line.

To do this, follow these steps:

  1. Evaluate the right-hand side as a value.
  2. Evaluate the left-hand side by either declaring a new variable or “looking up” the value of an existing variable.
  3. Assign (i.e., draw an arrow from) the LHS to the RHS.

Code Snippet #1

L1: Node<Integer> first = new Node<>(10);
L2: Node<Integer> temp = first.next;

Part 1

Assuming L1 and L2 have already been executed, trace through each of the following lines of code carefully to determine what memory looks like after each line.

Code Snippet #2

L3: first.next = new Node<>(100);
L4: first.next.next = temp;

Part 2

Assuming L1-L4 have already been executed, trace through the following loop in the same way as above.

Code Snippet #3

for (int i = 1; i < 5; i++) {
    Node<Integer> temp2 = first.next;
    first.next = new Node<>((i+1)*100);
    first.next.next = temp2;
}

Part 3

Consider the following recursive function:

private static <E> void addToEnd(Node<E> curr, Node<E> node) {
    if (curr == null) {
        curr = node;
    }
    else {
        addToEnd(curr.next, node);
    }
}

Assuming everything so far has already been executed, trace through the execution of the following method call.

Code Snippet #4

addToEnd(first, new Node<>(0));

Part 4

Assuming everything so far has already been executed, trace through the following loop in the same way as above.

Code Snippet #5

Node<Integer> curr = first.next;
while (curr != first) {
    if (curr.next == null) {
        curr.next = first;
    }
    curr = curr.next;
}