Linked Lists
Manipulate singly and doubly linked lists with pointer rewiring, dummy nodes and fast/slow pointers for cycles and middles.
Beginner · about 6 hours · difficulty 2/5
Learn first: Two Pointers, Recursion and Divide and Conquer
A linked list stores elements in nodes that point to the next node. Insertion and deletion at a known node are O(1), but access by index is O(n) and cache performance is poor. Interviewers use linked lists mainly to test careful pointer manipulation.
Core techniques
- Dummy (sentinel) head: create a fake node before the head so inserting or deleting the first node needs no special case.
- Iterative reversal: keep
prev,curr,next; pointcurr.nextto prev and advance. Practise until you can write it in one go. - Fast and slow pointers: slow moves one step, fast moves two. When fast reaches the end, slow is at the middle. If they ever meet, there is a cycle (Floyd's algorithm), and resetting one pointer to head finds the cycle start.
- Two-pointer gap: advance one pointer n steps first to find the n-th node from the end.
- Merge: merge two sorted lists with a dummy node; merge sort works naturally on lists.
Doubly linked lists
Each node has prev and next. Combined with a hash map this gives an O(1) LRU cache, one of the most asked design-flavoured coding questions.
Pitfalls
Losing the rest of the list by overwriting next too early, null pointer dereference on fast.next.next, and forgetting to update the tail. Draw boxes and arrows before coding.
Key concepts
- Singly vs doubly linked lists
- Dummy head node
- Iterative and recursive reversal
- Fast and slow pointers: Middle, cycle detection
- Floyd's cycle start
- Merging and sorting lists
- LRU cache with hash map + DLL
Mini project
Implement a singly linked list class, then solve 9 problems: Reverse Linked List, Merge Two Sorted Lists, Linked List Cycle II, Middle of the Linked List, Remove Nth Node From End, Reorder List, Palindrome Linked List, Add Two Numbers, and LRU Cache.
Check yourself
In Floyd's algorithm, after slow and fast meet inside the cycle, why does moving one pointer back to head and stepping both by one find the cycle's start?
Free resources
- LeetCode Explore: Linked List (LeetCode)
- VisuAlgo: Linked List (VisuAlgo)
- Linked list data structure (GeeksforGeeks)