Traversal and Read-Only Operations

A linked list here is built from ListItem objects:

public class ListItem {
  public int value;
  public ListItem next;

  public ListItem(int value) {
    this.value = value;
  }
}

The operations below traverse the list with a current reference, starting at head.

Solution
public static int size(ListItem head) {
  int count = 0;
  ListItem current = head;
  while (current != null) {
    count++;
    current = current.next;
  }
  return count;
}
Solution

size is for a linked list, since it has to visit every item to count them. An array stores its length as a single number, so reading it is .

Solution
public static boolean contains(ListItem head, int target) {
  ListItem current = head;
  while (current != null) {
    if (current.value == target) {
      return true;
    }
    current = current.next;
  }
  return false;
}
Solution

current.next != null. With current != null, the loop keeps advancing until current itself becomes null, which is one step past the last item. With current.next != null, the loop stops as soon as current.next is null, which happens while current is still on the last item, so addLast can change its next.

Solution

With a negative index, the loop condition i < index is false immediately, so current stays at head and get returns the head’s value, a plausible-looking result with no error at all. With an index past the end, current walks off the list and becomes null; the next step in the loop, or the final current.value, throws a NullPointerException. Neither outcome flags the index itself as the problem: the negative case fails silently, and the too-large case’s exception comes from chasing a null reference, not from a check on the index.

Solution

Best case is , when index is 0 and no steps are needed. Worst case is , when index is the last position and the traversal has to visit every item in the list.