Linked lists · Exercise 21 of 100
Find the first shared node
Two singly linked lists intersect when they reach the same node, even if earlier nodes hold equal values. For lists that end, count their lengths and advance the longer list's pointer by the difference. Both pointers now have the same distance left, so walking them together finds the first shared node if one exists.
Try it yourself
One list follows nodes Ash, Elm, Fir, Pine, Oak. Another follows Yew, Pine, Oak. Matching names refer to the same node, and Fir and Yew are separate nodes that both store 8. What is the name of the first shared node?
One-step hint
Sketch the lists as two paths, merging boxes only when their names match. Look for the first box both paths enter.
Worked solution
- The lengths are five and three. Move two links from Ash to Fir so the pointers start their joint walk at Fir and Yew.
- Fir and Yew only share a value. One link later both pointers reach the very same node, Pine.