Linked List
A treasure hunt where each clue says where the next one hides. To run it backwards you rewrite one clue at a time, keeping a finger on the next clue before you overwrite it. Reversing a list is the same: save next, flip, step on.
2 · Watch
Linked List in 60 seconds
3 · Now you drive
Reverse Linked List
4 · Your turn
Start from this
// Fake node in front, so the head isn't special.
const dummy = new ListNode(0, head);
let prev = dummy, curr = head;
while (curr) {
// Save this before rewiring cuts the link.
const next = curr.next;
rewire(prev, curr);
prev = curr;
curr = next;
}
// The real head, even if the old one moved.
return dummy.next;Easy ways to go wrong
- Cutting a link before saving the node after it.
- Skipping the dummy node, then special-casing the head.
- Reading .next on a node that might be null.
- Easy01
Reverse Linked List
The one you just watched. Write it from memory.
Repoint one arrow at a time, holding on to the rest of the chain.
- Time
- O(n)
- Space
- O(1)
- Easy02
Merge Two Sorted Lists
Warm-up: walk both lists, always taking the smaller head.
Compare the two heads and relink the smaller one.
- Time
- O(n + m)
- Space
- O(1)
- Easy03
Linked List Cycle
A fast pointer laps a slow one exactly when a loop exists.
A fast walker and a slow walker only meet if there’s a loop.
- Time
- O(n)
- Space
- O(1)
Also works with Two Pointers.
- Medium04
Reorder List
Find the middle, reverse the back half, then weave.
Find the middle, reverse the back half, then weave the two.
- Time
- O(n)
- Space
- O(1)
Also works with Two Pointers.
- Medium05
Remove Nth Node From End of List
Two pointers, n apart, walk to the end together.
Two walkers n apart: when the front one hits the end, the back one is in place.
- Time
- O(n)
- Space
- O(1)
Also works with Two Pointers.
- Hard06
Merge k Sorted Lists
Merge pairs again and again until one list is left.
Merge in pairs, halving the number of lists each round.
- Time
- O(n log k)
- Space
- O(1)
Also works with Heaps.