Revisit insertFront

Open the LinkedList.java file and find the insertFront method.

public Position<T> insertFront(T data) {
  Node<T> newFront = new Node<T>(data, this);

  Node<T> currFront = head;
  newFront.next = currFront;
  currFront.prev = newFront;
  head = newFront;

  numElements += 1;
  return newFront;
}

The implementation above fails to account for an edge case!

Exercise Identify the edge case and update the implementation.

Solution

The edge case is when the list is empty.

public Position<T> insertFront(T data) {
  if (head == null) {
    head = new Node<T>(data, this);
    tail = head;
    numElements += 1;
    return head;
  }

  Node<T> newFront = new Node<T>(data, this);

  Node<T> currFront = head;
  newFront.next = currFront;
  currFront.prev = newFront;
  head = newFront;

  numElements += 1;
  return newFront;
}