Linked Lists
A chain of boxes, each one knows only where to find the next
Imagine a treasure hunt. You find the first clue, it doesn't tell you where ALL the other clues are. It only tells you where the NEXT clue is. You find that one, it tells you the next, and so on. That's a linked list. A chain of boxes where each box knows exactly ONE thing: where to find the next box.
What is a Linked List?
Each box = a value + a pointer to the next box
๐ Click any node to inspect its contents.
Every node holds exactly 2 things:
val, the data (any value)
next, a pointer to the next node (or None at the end)
Like a treasure hunt, each clue only tells you where to find the next clue.
val, the data you care about (any value)next, a pointer to the next node (or None at the end)There is no "jump to node 5" shortcut. There is no length counter built in. Just: start at
head, follow the chain.class Node:
def __init__(self, val):
self.val = val # โ the value
self.next = None # โ the pointer (empty to start)
# Build: 1 โ 2 โ 3 โ None
a = Node(1)
b = Node(2)
c = Node(3)
a.next = b # 1 points to 2
b.next = c # 2 points to 3
# Traverse it, the same pattern you stepped through in the visual
curr = a
while curr:
print(curr.val) # โ 1, then 2, then 3
curr = curr.nextnew_node.next = head โ point new node at current headhead = new_node โ make new node the headThose 2 lines work whether the list has 4 nodes or 4 million. The rest of the list is completely untouched. That's the power of pointers.
A linked list has 1,000 nodes. You prepend a new node. How many existing nodes did you visit?
Why can't you do linked_list[5] to get the 6th element?
Practice Exercises
0/3 solvedWalk the Chain
You just stepped through a traversal in the interactive visual. Now do it in code, same exact pattern.
Start your "position" variable at head
curr = head
This is your finger on the chainCount the Nodes
Same traversal pattern as before, but now you count instead of print.
Start a counter
count = 0
Reverse the Chain
This is THE classic linked list interview question. The key insight: you're flipping arrows one by one. But if you flip an arrow without saving where it pointed, you lose the rest of the list forever.
Three pointers: prev=None, curr=head
prev is where we came from. curr is where we are.
prev = None | curr = head