LOGBOOK

HELP

Quiz Entry - updated: 2026.09.29

How do you insert a node at the head of a singly-linked list, and why does the order of the steps matter?

First point the new node at the old head (v.next ← head), then move head to the new node (head ← v), then increment size — $O(1)$.

addFirst: new node v links to the old first node, then head moves to v

* Step ① keeps the old list reachable through v before step ② moves head away from it. *

Algorithm addFirst(v)
  v.setNext(head)     { new node points to the old first node }
  head ← v            { head now points to the new node }
  size ← size + 1

Why the order matters: head is the only reference to the existing chain. If you did head ← v first, the old first node would no longer be referenced by anything, and v.setNext(head) would then make v point to itself. The rest of the list would be lost. Linking the new node before moving the entry point is the general rule for pointer surgery: never overwrite a reference until something else holds on to what it pointed to.

The operation touches a constant number of references regardless of the list length, so it runs in $O(1)$. It also works on an empty list: head is null, so v.next becomes null and v is the only node.

From Quiz: ADS / Linear Data Structures: Lists, Stacks, Queues, Deques, Iterators | Updated: Sep 29, 2026