I have been asked recently in a job interview to develop an algorithm that can determine whether a linked list is cyclical. As it’s a linked list, we don’t know its size. It’s a doubly-linked list with each node having ‘next’ and ‘previous’ pointers. A node can be connected to any other node or it can be connected to itself.
The only solution that I came up at that time was to pick a node and check it with all the nodes of the linked list. The interviewer obviously didn’t like the idea as it is not an optimal solution. What would be a better approach?
The general solution is to have 2 pointers moving at different rates. They will eventually be equal if some portion of the list is circular. Something along the lines of this:
Blatantly stolen from here: http://ostermiller.org/find_loop_singly_linked_list.html