Return a Position!
Here is the implementation of addFirst
from an earlier exercise:
public void addFirst(T data) {
Node<T> node = new Node<>(data);
node.next = head;
head.prev = node;
head = node;
}
Exercise Update addFirst
to return the newly added node (position) which contains the given data value.
public Position<T> addFirst(T data) {
// TODO Implement Me!
return null;
}
Solution
public Position<T> addFirst(T data) {
Node<T> node = new Node<>(data);
node.next = head;
head.prev = node;
head = node;
return node;
}
Notice we can directly return a value of type Node
where a Position
is expected. This works because of "type substitution".