Open
Description
The broken code:
private void addAsHead(Node<T> newNode) {
newNode.next = head;
head = newNode;
}
Please consider the following example:
LinkedList<Integer> list = new LinkedList<>();
list.add(0, 100);
list.add(144);
This code will result in a NullPointerException if we define the add method as follows:
@Override
public void add(T element) {
requireNonNull(element);
Node<T> newNode = new Node<>(element);
if(head == null){
head = tail = newNode;
} else {
tail.next = newNode;
tail = tail.next;
}
size++;
}
It's necessary to reassign tail, as shown in the "completed" branch.
Metadata
Metadata
Assignees
Labels
No labels