Quiz Entry - updated: 2026.09.29
How do you remove the first node of a singly-linked list?
Check that the list is not empty, keep a temporary reference t to the old head, move head to head.next, cut the old node loose with t.next ← null, and decrement size — $O(1)$.
* t keeps the old first node in hand while head moves on to the second. *
Algorithm removeFirst()
if head = null then indicate an error: the list is empty
t ← head { keep the old first node }
head ← head.getNext() { head now points to the second node }
t.setNext(null) { unhook the old node from the list }
size ← size − 1
Each line has a reason:
- The empty check comes first because
head.getNext()on anullhead would crash. tholds on to the old first node, so it can be unhooked and (in a real method) its element returned.t.setNext(null)removes the removed node's link into the list. It is not needed for correctness, but it stops the old node from keeping the rest of the list reachable through a stray reference, which helps the garbage collector.
Like addFirst, this is a constant number of reference updates: $O(1)$.