Follow the next pointer.
Understand node-based sequences and why constant-time local edits have conditions.
01 Model the idea
A singly linked list stores nodes that each point to the next node. It does not provide efficient arbitrary indexed access: reaching position k requires following links. Inserting after a known node is constant time, but finding that node may take linear time. Implementing this structure is a useful exercise even though Python’s built-in list is usually a more practical default.
Every reachable next link preserves the intended chain.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
CREATE nodes with next references
TO insert after a node: preserve its next link
POINT the known node at the new node
FOLLOW links until the end03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
from dataclasses import dataclass
@dataclass
class Node:
value: str
next: "Node | None" = None
head = Node("Build", Node("Test"))
head.next = Node("Review", head.next)
current = head
while current is not None:
print(current.value)
current = current.nextBuild Review Test
- 1
head names the first node. Each next reference represents one edge in the chain, and None marks the end.
- 2
The insertion preserves the old next reference by passing it to the new node before assigning head.next. Losing that reference would disconnect the rest of the list.
- 3
Memory overhead, locality, and pointer traversal matter in real implementations. The attractive complexity of one local operation does not make linked lists universally faster.
04 Count the cost
O(n) traversal; O(1) insertion after a known node
O(n) node storage; O(1) traversal auxiliary
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Write a function that counts nodes without converting the list into a Python list.
Reveal one possible solution +
from dataclasses import dataclass
@dataclass
class Node:
value: int
next: "Node | None" = None
head = Node(1, Node(2, Node(3)))
count, current = 0, head
while current is not None:
count += 1
current = current.next
print(count)06 Check your reasoning
Is finding the kth node constant time?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.