Given a linked list with at least 3 nodes, return the middle element of that list in a single pass through. You're not allowed to reiterate through the list. Bonus points for not copying all the elements of the list to an array.
Given a linked list with at least 3 nodes, return the middle element of that list in a single pass through. You're not allowed to reiterate through the list. Bonus points for not copying all the elements of the list to an array.
Permalink: http://problemotd.com/problem/middle-element/
Content curated by @MaxBurstein
Comments:
pypy - 10 years, 6 months ago
Python 2.7. Same algorithm can be used to check for loops in a linked list I think. Just add a check to see if slow == fast in the loop.
reply permalink
Max Burstein - 10 years, 6 months ago
Nicely done
reply permalink
Rawin - 10 years, 6 months ago
I love this one!
reply permalink
Nick Krichevsky - 10 years, 6 months ago
Got it in C++. I think mine might be a bit strange, since I had to add an exception for the length being even. If the length is even, there is technically no middle of the list.
reply permalink
Max Burstein - 10 years, 6 months ago
Very true. Good simple code and handles all cases. I like it.
reply permalink