- Understand references
- Insert without shifting elements
- Compare with arrays
The minimal node
The list knows its head. From there, each reference leads to the next node until null.
type Node<T> = { value: T; next: Node<T> | null };
const head: Node<number> = {
value: 10,
next: { value: 20, next: null }
};Front insertion is constant
Creating a node that points to the current head and replacing the head costs O(1). Finding position twenty still costs O(n).
function prepend(list, value) {
return { value, next: list };
}When to use it
It helps with frequent insertion or deletion when you already have the right reference. For random access, an array is generally better and cache-friendly.
Reverse a list
Traverse a list and reverse every reference without creating another array.
Show a hint
Keep previous, current, and next.