LINKED LISTS · 9 MIN
Linked Lists
Each node holds a value and a pointer to the next node.
BYTE explains
- Adding at the head is O(1); finding the k-th item is O(n).
- Reverse a list by flipping each next pointer while walking forward.
- Fast/slow pointers find the middle or detect a cycle.
Real world: A treasure hunt: each clue tells you where the next one is.
Code
class Node:
def __init__(self, v, nxt=None):
self.v, self.next = v, nxt
def reverse(h):
prev = None
while h:
h.next, prev, h = prev, h, h.next
return prev
h = reverse(Node(1, Node(2, Node(3))))
out = []
while h:
out.append(h.v); h = h.next
print(out)Output ›
[3, 2, 1]Try it in the online compiler →Checkpoint quiz
Inserting at the head of a linked list is…