All topics

Linked Lists

Pointer manipulation: reverse, merge, detect cycles, design caches.

6 pages, free to read

  1. 1

    Linked list basics

    Beginner

    A linked list is a chain of nodes where each node holds a value and a pointer to the next node, so you can insert or remove at a known position in O(1) but must walk O(n) to reach the k-th item.

    8 min read
  2. 2

    Reversing a linked list

    Beginner

    Walk the list once with three pointers (prev, cur, next) and flip each node's next pointer to point backwards, reversing the list in O(n) time and O(1) space.

    8 min read
  3. 3

    Cycles & the middle node

    Intermediate

    Move a slow pointer one step and a fast pointer two steps: if they meet there is a cycle, and when the fast one reaches the end the slow one is at the middle, all in O(n) time and O(1) space.

    10 min read
  4. 4

    Merging & splitting lists

    Intermediate

    Merge two sorted lists by repeatedly attaching the smaller head to a growing tail, split a list at its middle with fast and slow pointers, and combine the two to merge sort a linked list in O(n log n).

    10 min read
  5. 5

    The dummy-node technique

    Beginner

    Put a fake node in front of the real head so that every real node has a predecessor; then inserting or deleting at the head needs no special case and you simply return dummy.next.

    7 min read
  6. 6

    Designing an LRU cache

    Advanced

    An LRU cache combines a hash map (key to node, for O(1) lookup) with a doubly linked list ordered by recency (for O(1) move-to-front and evict-from-back), so get and put are both O(1).

    12 min read