
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 forinsert(0, x).) - But reaching item number
iis 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
listis 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:
push_frontlinks the new node in front of the old head.pop_frontmovesheadto the second node and returns the old value.to_listwalks the chain from head toNone.__len__returns the stored size.
Replace each ___ so the Chain class works:
push_frontlinks the new node in front of the old head.pop_frontmovesheadto the second node and returns the old value.to_listwalks the chain from head toNone.__len__returns the stored size.
main.py Python sleeping
Press Run to try your code, then Check to test it.