Linked Lists — Nodes and Pointers
Imagine a treasure hunt where each clue tells you where the next clue is hidden. You can hide clues anywhere in town, and adding a new clue in the middle only means rewriting one old clue. But to reach clue 50, you have no choice: you follow clues 1 to 49 first. That is a linked list.
The rule
Each node holds a value and where the next node lives.
A linked list does not need one big block of memory. Each element sits in its own small node, which can be anywhere in memory. A node holds two things:
- the value,
- a pointer: the memory address of the next node.
The list itself only remembers the address of the first node, called the head. The last node's pointer is empty (null, None, nullptr), which marks the end.
class Node:
def __init__(self, value):
self.value = value
self.next = None # address of the next node, or nothingBecause order lives in the pointers, not in positions, a linked list has the opposite strengths of an array:
| Array | Linked list | |
|---|---|---|
| Reach element k | one jump | walk k pointers |
| Insert after a node you hold | shift everything after | change two pointers |
| Extra memory | none | one pointer per node |
A doubly linked list also stores a pointer back to the previous node, so you can walk both ways at the price of a second pointer in every node.