Nodes and pointers
In the visualizer, choose List type and compare Insert at position, Delete at position, and Search for value. Operations at the front need no traversal; an operation at a later position must walk through the preceding nodes first.
Worked example: insert after a node
Suppose P points to the node before the insertion location and N is the new node. First set N.next to the node that followed P; then set P.next to N:
new_node.next = previous.next
previous.next = new_node
If the order is reversed, the original remainder of the list can become unreachable. The operation is constant time once previous is known; finding that node by position still takes time proportional to the number of nodes traversed.
Singly linked, doubly linked, or array
- Singly linked: one
next pointer per node; simple and lower in pointer overhead, but backward movement requires another traversal. - Doubly linked: each node has
next and prev; supports backward traversal and deletion when the node is already known, at the cost of more memory and pointer updates. - Dynamic array: fast indexed access and good cache locality; inserting near the front shifts later elements, while append is amortized constant time.
| Operation | Linked list by index | Dynamic array |
|---|
| Read item at index i | O(n) | O(1) |
| Insert at front | O(1) | O(n) |
| Insert after a known node | O(1) | O(n) in general |
| Search by value | O(n) | O(n) |
The table separates locating a position from changing pointers. Inserting at an arbitrary index in a linked list is not O(1) if the list must first be traversed to find it.
When linked lists are useful
Use them when code already holds node references and needs frequent splicing, or when implementing structures that need predictable local insertion and deletion. A doubly linked list paired with a hash map is a common design for an LRU cache: the map finds a node and the list moves it to the most-recently-used position.
For general application data, a dynamic array is often simpler and faster because contiguous memory is cache-friendly. Big-O counts operations but not the cost of pointer chasing or memory allocation.
Common mistakes with Linked Lists
- Expecting random access: index lookup still walks the list.
- Losing the next pointer: save it before rewiring links.
- Ignoring the predecessor: singly linked deletion usually needs the node before the one being removed.
- Forgetting edge cases: empty list, head deletion, tail updates, and a one-node list need explicit handling.