Linked Structures
Build a Singly Linked List
Construct a singly linked list by allocating one node per value and
chaining next pointers. Establishes the node + head + tail model used by
every later linked-list lesson.
Algorithm
Canonical input [10, 20, 30, 40] builds the chain
head -> 10 -> 20 -> 30 -> 40 -> null with one node appended per step.
Basic Implementation
basic.py
class Node:
__slots__ = ("value", "next")
def __init__(self, value):
self.value = value
self.next = None
values = [10, 20, 30, 40]
head = None
tail = None
for value in values:
node = Node(value)
if head is None:
head = node
else:
tail.next = node
tail = node
Complexity
- Time: O(n) with a tail pointer
- Space: O(n)
Implementation notes
- Python: a small class with
__slots__ = ("value", "next")is the idiomatic Node. A dataclass would work too. - The replay never shows object identity; nodes are labelled
node(<value>)and the chain view is rendered as1 -> 2 -> ... -> null.
node chain
Each node carries a value and a `next` reference to the following node or `None`.