DLL Operation: Prepend
Suppose we have the following DLL and we want to add a new node to the front of it.
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 data) {
Node<T> node = new Node<>(data);
node.next = head;
head.prev = node;
head = node;
}
Caution: the implementation above fails to account for edge cases!