Singly linked list
easy 18 minA singly linked list is a chain of nodes where each node holds a value and a pointer to the next node.
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
Follow the clues: each node only knows where the next one is.
A train. The engine is the head, every car is a node and each coupler is a next pointer to the car behind. Coupling a car at the front is quick, but to reach car 5 you walk through cars 1 to 4, and the last car's coupler hangs free like NULL.
Cheat sheet
- Insert at head
- O(1)
- Insert at tail
- O(n), O(1) with a tail pointer
- Insert or delete at k
- O(k), stop at k - 1
- Delete head
- O(1)
- Delete tail
- O(n), even with a tail pointer
- Search, access by index
- O(n)
- Reverse
- O(n) time, O(1) space
- Space
- O(n), one pointer per node
- Empty list
- head is None
Spot it when you see
- The input is a ListNode head.
- "In place" or "O(1) extra space" on a chain of nodes: think pointer rewiring.
- Middle, cycle, or kth from the end: slow and fast pointers.
- Merging or splitting sequences without copying.
- The head might change: add a dummy node.
- Frequent inserts and deletes at the front with no need for indexing.
Tricks that stick
- LINK: Linear chain, Index by traversal only, Next pointer, Knows only its neighbour.
- Rhyme: "Save the next before you switch, or you'll lose your list in a glitch. Point back to prev with care, and your reversal will get you there."
- Memory palace: front door is insert at head (instant), living room is traverse (walk through), bathroom is delete (wash it away), bedroom is find middle (the centre), back door is reverse (go backwards).
- Insert order: link the new node forward first, then rewire the old one.
- Delete is a bypass: prev.next = prev.next.next.
- Draw the boxes and arrows before writing a line of pointer code.
Do not forget
- Overwriting current.next before saving it, which loses the rest of the list.
- Reading head.val or head.next without checking for None.
- Walking pos steps instead of pos - 1 when inserting or deleting.
- Forgetting to move head, or forgetting to return the new head from a function.
- Looping forever on a list that has a cycle.
- Comparing nodes with == when you mean is, or comparing values when you mean nodes.