LOGBOOK

HELP

Quiz Entry - updated: 2026.09.29

How do you insert a node at the end of a singly-linked list in $O(1)$?

Keep a tail reference: set v.next ← null, link the old tail to it (tail.next ← v), then move tail ← v. Without a stored tail you would have to walk the whole list first, which is $O(n)$.

addLast: v points to null, the old tail links to v, tail moves to v

* All three writes happen at the far end; head and the middle of the list are never visited. *

Algorithm addLast(v)
  v.setNext(null)     { the new node will be the last one }
  tail.setNext(v)     { the old last node points to it }
  tail ← v            { tail moves to the new node }
  size ← size + 1

The whole point of storing tail next to head is this operation. A singly-linked list can only be walked forwards from the head, so finding the last node without a tail reference means following all $n$ links. With it, the end is one reference away.

Gotcha: on an empty list tail is null, so tail.setNext(v) would fail. A real implementation checks for that case and sets both head and tail to v.

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