Prepend Operation
Suppose we have the following linked list and want to add a new node to its front.
Exercise Complete the implementation of the addFirst
method that creates a node and adds it to the front of the list.
public void addFirst (T data) {
// TODO Implement Me!
}
Hint: Use the following visualization as a guidance:
Solution
public void addFirst(T t) {
Node<T> node = new Node<>(t);
// node.next = null; // no need: done by default!
node.next = head;
head = node;
}