Notes
All notes

Linked Lists (DSA #3)

Inserting into the middle of an array is expensive because the elements after it must all shift. A linked list makes a different bargain: each element stores a pointer to the next, so inserting is just rewiring two pointers — no shifting — but finding the insertion point now requires walking the chain. Understanding that trade is the whole chapter.

Linked lists also introduce the pointer as a thinking tool. Reversal, cycle detection, and merging sorted lists are all exercises in moving a few references without losing the rest of the chain. Cross-reference: the companion problem note Reverse a Linked List dries the reversal with diagrams.

The node

A linked list is a sequence of nodes, each holding a value and a reference to the next node:

class Node:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

The head is the only handle you keep. If you lose it, the list is unreachable. A doubly linked list adds prev for backward traversal.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, minimum width=1.05cm, minimum height=0.8cm, font=\large\bfseries},
  a/.style={->, thick}]
  \node[n, fill=blue!12] (n1) at (0,0) {1};
  \node[n, fill=blue!12] (n2) at (1.7,0) {2};
  \node[n, fill=blue!12] (n3) at (3.4,0) {3};
  \node[n, fill=gray!12] (nn) at (5.1,0) {$\varnothing$};
  \draw[a] (n1) -- (n2); \draw[a] (n2) -- (n3); \draw[a] (n3) -- (nn);
  \node[font=\scriptsize\ttfamily, text=black!60] at (0,0.85) {head};
\end{tikzpicture}

The operation table

Operation Array Linked list
Access \(i\)-th \(O(1)\) \(O(n)\)
Search \(O(n)\) \(O(n)\)
Insert/delete at head \(O(n)\) \(O(1)\)
Insert/delete given a node \(O(n)\) \(O(1)\)
Insert/delete at tail \(O(1)\) amortized \(O(1)\) with tail pointer
Memory overhead low a pointer per node

The headline: linked lists win on insertions and deletions at known positions, arrays win on random access. Neither dominates.

Traversal and insertion

Walking the list is a while loop on curr, never on indices:

def length(head):
    count, curr = 0, head
    while curr:
        count += 1
        curr = curr.next
    return count

Inserting after a known node is pure pointer rewiring:

def insert_after(node, val):
    node.next = Node(val, next=node.next)

Deleting a known node requires its predecessor (in a singly linked list), which is why deletion “given a node” often means copying the next node’s value then skipping it:

def delete_node(node):        # node is not the tail
    node.val = node.next.val
    node.next = node.next.next

This last trick is worth remembering: in a singly linked list you can delete a node in \(O(1)\) by overwriting it with its successor and unlinking that successor, sidestepping the search for the predecessor.

Reversal: three pointers, one pass

Reversing a linked list is the canonical pointer exercise. The idea: walk the list once, and at each step point the current node backward instead of forward. You need three references — the node you are on (curr), the one before it (prev), and the one after (nxt, saved before you break the link).

def reverse(head):
    prev, curr = None, head
    while curr:
        nxt = curr.next      # 1. save the rest
        curr.next = prev     # 2. flip the link
        prev = curr          # 3. advance prev
        curr = nxt           # 4. advance curr
    return prev              # new head

Order matters: if you flip curr.next before saving nxt, the rest of the list is lost. The companion note Reverse a Linked List walks this through four TikZ frames; the invariant is that everything to the left of curr is already reversed.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, minimum width=1.0cm, minimum height=0.78cm, font=\large\bfseries},
  done/.style={n, fill=green!30}, cur/.style={n, fill=orange!40, very thick},
  a/.style={->, thick}]
  \node[done] (n1) at (0,0) {1}; \node[done] (n2) at (1.7,0) {2};
  \node[cur]  (n3) at (3.4,0) {3}; \node[n] (n4) at (5.1,0) {4};
  \draw[a] (n2.west) -- (n1.east);       % reversed part
  \draw[a] (n1.west) -- ++(-0.6,0);      % null
  \draw[a] (n3.west) -- (n2.east) node[midway, above, font=\scriptsize] {still forward};
  \draw[a] (n3) -- (n4);
  \node[font=\scriptsize\ttfamily] at (3.4,0.9) {curr};
  \node[font=\scriptsize\ttfamily, text=black!60] at (1.7,0.9) {reversed};
\end{tikzpicture}

Fast and slow pointers

Two references moving at different speeds solve several problems without knowing the length in advance.

Finding the middle: advance slow one step and fast two. When fast reaches the end, slow is at the middle.

def middle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow

Detecting a cycle (Floyd’s tortoise and hare): if there is a cycle, the fast pointer eventually laps the slow one and they meet. If it ends, there is no cycle.

def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:      # they met inside a cycle
            return True
    return False

The reason the meeting works is arithmetic: inside a loop of length \(C\), the fast pointer gains one position on the slow pointer each step, so it must eventually catch it. Once they meet, the cycle’s start can be found by resetting one pointer to the head and moving both one step at a time until they meet again — a neat follow-up worth trying.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.62cm, font=\small\bfseries, inner sep=0pt},
  a/.style={->, thick}]
  \node[n, fill=blue!12] (a) at (0,0) {1};
  \node[n, fill=blue!12] (b) at (1.2,0) {2};
  \node[n, fill=blue!12] (c) at (2.4,0) {3};
  \node[n, fill=blue!12] (d) at (3.6,0) {4};
  \node[n, fill=blue!12] (e) at (4.8,0) {5};
  \draw[a] (a) -- (b); \draw[a] (b) -- (c); \draw[a] (c) -- (d); \draw[a] (d) -- (e);
  \draw[a] (e) to[bend left=50] (c);
  \node[font=\scriptsize\ttfamily, text=green!45!black] at (2.4,-0.85) {slow};
  \node[font=\scriptsize\ttfamily, text=orange!75!black] at (3.6,0.85) {fast};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (2.4,-1.4) {fast gains one step per tick -> catches slow inside the loop};
\end{tikzpicture}

Merging two sorted lists

A classic two-pointer merge (the heart of merge sort). Walk both lists, always taking the smaller head:

def merge(a, b):
    dummy = tail = Node(0)          # sentinel simplifies edge cases
    while a and b:
        if a.val <= b.val:
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b              # attach the remainder
    return dummy.next

The dummy node removes the “is this the first node?” special case — a habit worth carrying into tree and list problems.

Pitfalls

QQuestionSelf-check

Why does reversal need a third pointer? How does Floyd’s algorithm detect a cycle without extra space?

ASolution

Reversal needs to save the next node before flipping the current link, or the rest of the list becomes unreachable. Floyd’s uses a slow pointer (one step) and a fast pointer (two steps); if there is a cycle, the fast pointer gains one position each tick and must eventually meet the slow one, using only two references.

Next: Stacks (DSA #4) — the last-in-first-out structure behind undo, parsing, and the call stack.