Detecting cycles in a single linked list is a well known problem. I know that this question has been asked a zillion times all over the internet. The reason why I am asking it again is I thought of a solution which I did not encounter at other places. (I admit I haven’t searched that deeply either).
My solution is:
Given a linked list and pointer to some node, break the link between node and node->next();
Then start at node->next() and traverse till either you hit an end (which means there was no loop) or till you reach at node which means there was a loop.
Is there anything wrong/good about above solution ?
Note: Do join the link back once you are done.
That will work to detect complete cycles (i.e., cycles with a period of the whole list), e.g.:
But what if we have a cycle somewhere else in the list?
e.g.,
I can’t see that your algorithm will detect the cycle in this case.
Keep in mind that to detect the first case, we need not even break the link. We could just traverse the list and keep comparing the
nextlink for each node with the head element to see if we’d started back at the start yet (or hit the end).