Skip to the page

Linear patterns · mid

Linked lists in JavaScript

A linked list is nodes with next pointers, so problems are about re-wiring pointers safely. JavaScript has no built-in linked list: write a small node class, keep a reference before you overwrite next, use a dummy head for edge cases, and use fast and slow pointers for the middle and for cycles.

The notes

What you must know

  • Reverse: prev = null; while (cur) { next = cur.next; cur.next = prev; prev = cur; cur = next; } return prev.
  • Dummy head node removes special cases when the head changes (merge, remove elements).
  • Fast/slow: slow moves 1, fast moves 2. Middle = slow when fast reaches the end; cycle exists if they meet (Floyd).
  • Copy list with random pointer: Map old → new in two passes, or interleave copies for O(1) extra space.
  • Doubly linked list + Map = O(1) LRU cache (when you are not allowed to rely on Map order).
  • Frontend links: the React Fiber tree links child/sibling/return; undo history can be a list.
  • A node is a plain object { val, next } or a small class with constructor(val, next = null). The list ends at null, so loop with while (cur) and check cur.next before reading cur.next.next.

The red pen

Common traps: mistake → fix

  • Mistake: Set cur.next = prev first

    Fix: you lose the rest of the list; save next before re-wiring.

  • Mistake: Handle the empty list later

    Fix: null head breaks most loops; test [] and [1].

  • Mistake: Cycle detection needs a Set of visited nodes

    Fix: Floyd's algorithm needs O(1) space.

Easy to hard

Questions interviewers ask, easy to hard

  1. Reverse a linked list, iteratively and recursively.
  2. Find the middle node in one pass.
  3. Detect a cycle with O(1) extra space.
  4. Copy a list with random pointers.
  5. Design an LRU cache without relying on Map order.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview