Get Operation

  • Trace the basic operations of a (singly) linked list implementation.
  • Understand the basic operations of a (singly) linked list well enough to implement them.

Suppose we have a linked list with $n$ elements (nodes), and we want to get the data stored in the $k^{th}$ element (at index $k-1$).

Exercise Complete the implementation of the get method which returns data stored at a given index.

public T get(int index) {
  return null; // TODO Implement me!
}

Hint: you cannot directly jump to $K^{th}$ node. You need to start at the head and follow the next references to get there!

Solution
public T get(int index) {
  return find(index).data;
}

// PRE: 0 <= index < numElements 
private Node<T> find(int index) {
  Node<T> target = head;
  for(int counter = 0; counter < index; ounter++) {
    target = target.next;
  }
  return target;
}

Caution: the implementation above fails to account for an edge case!