LOGBOOK

HELP

Quiz Entry - updated: 2026.09.29

How do you insert a node v after a given node u in a doubly-linked list?

Remember u's old successor w ← u.next, point v at both neighbours (v.prev ← u, v.next ← w), then point the neighbours at v (w.prev ← v, u.next ← v) — four reference writes, $O(1)$.

addAfter: v links to u and w, then w and u link back to v

* v is wired to both neighbours first; only then are u and w redirected to v. *

Algorithm addAfter(u, v)       { insert v after u }
  w ← u.getNext()
  v.setPrev(u)
  v.setNext(w)
  w.setPrev(v)
  u.setNext(v)
  size ← size + 1

Why this order: the first thing to do is save w. The last line, u.setNext(v), overwrites u's only reference to w; if that happened first, w would be lost. Setting up the new node's own links first and redirecting the old neighbours last follows the same rule as addFirst on a singly-linked list: never overwrite a reference until the node it points to is held somewhere else.

Why it is $O(1)$: you already have u in hand, and every other node involved is one link away. Nothing is shifted and nothing is searched. This is the operation where linked lists beat arrays outright: inserting into the middle of an array means moving every element behind the gap.

Tip: addFirst and addLast with sentinels are this same operation with u = header and u = trailer.prev.

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