A chain of nodes
A linked list stores items in separate little boxes called nodes. Each node holds a value and a link (pointer) to the next node. The first node is the head; the last node points to None.
Think of it like this: A treasure hunt: each clue tells you where the next clue is hidden. You can't jump to clue 5 – you have to follow clues 1, 2, 3 and 4 to get there.
class Node:
def __init__(self, value):
self.value = value
self.next = None
# build 10 -> 20 -> 30
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
current = head
while current is not None: # walk the chain
print(current.value)
current = current.nextOutput
10 20 30
Building from a Python list
class Node:
def __init__(self, value):
self.value = value
self.next = None
def build(values):
head = None
for v in reversed(values): # add to the front, from the last value back
node = Node(v)
node.next = head
head = node
return head
def show(head):
parts = []
while head:
parts.append(str(head.value))
head = head.next
return " -> ".join(parts) + " -> None"
print(show(build([3, 1, 4, 1, 5])))Output
3 -> 1 -> 4 -> 1 -> 5 -> None
Array vs linked list
| Operation | Array (Python list) | Linked list |
|---|---|---|
| get the i-th item | O(1) | O(n) – follow the links |
| add/remove at the front | O(n) | O(1) |
| add/remove after a node you already have | O(n) | O(1) |
| memory | one block | extra pointer in every node |
Remember: Linked lists are great when you add and remove at the front a lot, and bad when you need to jump to position i.