programmingconcepts

§ 2.3 · Data structures

Linked lists

A chain of nodes where each one holds a value and a pointer to the next, so items can be added without shifting anything.

A linked list stores each value in its own node, and every node points to the next one. Adding or removing a node at the front, or after a node you already hold, takes O(1) because only pointers change. Reaching the k-th item means following k pointers from the head, so access and search take O(n).

Prepend
O(1)
Append
O(n) with only a head
Find or remove
O(n)
Read item i
O(n)
Requires
Arrays
class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next


class LinkedList:
    def __init__(self):
        self.head = None

    def prepend(self, value):
        self.head = Node(value, self.head)

    def append(self, value):
        node = Node(value)
        if self.head is None:
            self.head = node
            return
        cur = self.head
        while cur.next is not None:
            cur = cur.next
        cur.next = node

    def remove(self, value):
        prev, cur = None, self.head
        while cur is not None and cur.value != value:
            prev, cur = cur, cur.next
        if cur is None:
            return False
        if prev is None:
            self.head = cur.next
        else:
            prev.next = cur.next
        return True

step 1 / 1checkingchanging

Fig. 2.3. Pick a value and an operation. Blue marks the node being checked; orange marks the pointer that changes. Prepend is instant; append and remove have to walk.

Intuition

A treasure hunt where each clue tells you where the next one is hidden. You can’t jump to clue 7; you have to follow clues 1 to 6. But adding a new clue at the start is easy: write it so it points at the old first clue.

That’s a linked list. Unlike an array, the items don’t sit side by side in memory, so inserting never shifts anything. The price is that finding item i means following i pointers.

How it works

Each node holds a value and next, a pointer to the following node (or null at the end). The list itself only stores head, the first node.

  • Prepend: make a node pointing at the current head, then make it the head. Two pointer changes, O(1).
  • Append: walk from the head until next is null, then point that node at the new one. O(n), unless you keep a tail pointer.
  • Remove: walk with two pointers, prev and cur, until cur holds the value. Then point prev.next past cur. If cur is the head, move the head instead.

Arrays or linked lists?

Operation Array Linked list
Read item i O(1) O(n)
Insert or remove at the front O(n) O(1)
Insert or remove after a node you already have O(n) O(1)
Memory per item Just the value Value plus a pointer
Cache friendliness Excellent Poor: nodes are scattered

In practice, arrays win most of the time because modern CPUs read neighbouring memory very fast. Linked lists shine when you insert and remove in the middle a lot and already hold a pointer to the spot, as in LRU caches and many kernel data structures.

Common mistakes

  1. Losing the rest of the list. Changing cur.next before saving it drops every node after cur.
  2. Forgetting the empty and one-node cases. Removing the head, or appending to an empty list, needs its own branch.
  3. Walking off the end. Check cur for null before reading cur.value.
  4. Using a linked list for random access. If you index by position, use an array.

In other languages

Language Built-in linked list
Python None; collections.deque covers most uses
JavaScript None
Java LinkedList (doubly linked)
C None; written by hand everywhere
Go container/list (doubly linked)
Rust std::collections::LinkedList (doubly linked; rarely the best choice)

Check yourself

Check yourself

With only a head pointer, which operation is O(1) on a singly linked list?

Check yourself

To remove 7 from 3 → 7 → 12, which pointer changes?

Sources

  • Donald Knuth, The Art of Computer Programming, Vol. 1, section 2.2.3, “Linked Allocation.”
  • Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, section 10.2, “Linked lists” (3rd edition).

Newsletter

One new concept each week, by email.

Signup opens soon.