Implementing pop, top, and push
The pop and top operations start with the same contract check as in ArrayStack. After the check, each is one line.
@Override
public void pop() {
if (isEmpty()) {
throw new NoSuchElementException();
}
head = head.next; // unlink the old top; the next node is the new top
}
@Override
public T top() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return head.value; // the top item is in the head node
}
The push operation does the same two things as ArrayStack’s push: reject null, then add the item to the top.
@Override
public void push(T item) {
if (item == null) {
throw new IllegalArgumentException();
}
Node<T> newNode = new Node<>(item);
newNode.next = head; // the old top comes after the new item
head = newNode; // the new item is now the top
}
That completes LinkedStack.