- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Linked List Two Pointer Problems
Linked Lists
Linked List Two Pointer Problems
You cannot index into a linked list, so every question about position is answered with two pointers moving at different speeds. Learn the three shapes and you have covered most of what gets asked.
Why speed differences work
If one pointer moves twice as fast as another, then when the fast one reaches the end, the slow one is exactly halfway. Every trick here is a variation on that.
Find the middle
Fast and slow
javascript
function middle(head) {
let slow = head
let fast = head
while (fast && fast.next) {
slow = slow.next
fast = fast.next.next
}
return slow
}