Fill in

The Lantern Chain

A linked list stores items in nodes. Each node holds a value and a reference to the next node. The list itself only remembers the first node: the head.

head -> [Reef] -> [Mill] -> [Peak] -> None
class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

head = Node("Reef", Node("Mill"))
print(head.next.value)   # Mill

Why bother?

  • Adding or removing at the front is O(1): just re-point head. (A Python list must shift everything for insert(0, x).)
  • But reaching item number i is O(n): you must walk the chain.

To walk the chain, start at head and follow .next until you reach None.

Pip tip: Python's own list is a dynamic array, not a linked list. Linked lists matter for understanding trees, graphs and many interview problems. They all use "nodes pointing at nodes".

Assignment

Replace each ___ so the Chain class works:

  1. push_front links the new node in front of the old head.
  2. pop_front moves head to the second node and returns the old value.
  3. to_list walks the chain from head to None.
  4. __len__ returns the stored size.