Linked Lists

Pointer manipulation fundamentals: reversing, merging, finding the middle, removing the n-th node from the end and detecting cycles, each in O(n) time and O(1) extra space.

Overview

A linked list stores a sequence as separate nodes. Each node holds a value and a pointer (a reference) to the next node. The list itself is just a pointer to the first node, called the head. The last node points to nothing (null in Java and JavaScript, None in Python). Picture the list 1, 2, 3, 4: you hold only the head, which points to node 1. Node 1 points to 2, 2 points to 3, 3 points to 4, and 4 points to null. To reach node 3 you must walk through 1 and 2 first, because each node knows only where the next one lives.

Linked lists test one skill: changing pointers in the right order without losing part of the list. The problems are short, but one wrong assignment cuts the list or builds a loop. Nearly every problem is solved by a small set of moves: a dummy head, reversal, two pointers at different speeds, two pointers with a gap, and merging. This chapter covers each move in turn, after a look at what a linked list costs compared with an array.

Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.

Linked list or array

The rule: an array can jump to any index at once; a linked list can only walk from the head. In exchange, once you hold a node, the list can add or remove the node after it by changing one or two pointers, with no shifting.

That trade shows up in every operation.

  • Read index i: O(1) for an array, O(i) for a singly linked list, which must walk from the head.
  • Insert or delete at the front: O(n) for an array, which must shift everything; O(1) for the list, which changes one pointer.
  • Insert or delete after a node you hold: O(n) for the array, which shifts the rest; O(1) for the list, which relinks.
  • Append at the end: O(1) amortized for an array. A list matches that only if it keeps a tail pointer; without one, it walks to the end in O(n).
  • Search for a value: O(n) in both, since neither knows where the value is.

Memory is where arrays pull ahead. An array is one block, which is cache friendly. A list is scattered nodes, and each one pays for a pointer on top of its value.

> [!NOTE] > In practice arrays are faster for most workloads, because reading neighbors in memory is cheap for the CPU cache. Linked lists win when you splice nodes in and out often and already hold a pointer to the spot, as in an LRU (least recently used) cache.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio