Find the existence of a loop in a linked list

Question: Find if given linked list has a loop or not. If a list has a loop, then you will never stop traversing the list and visit the same set of elements again and again. For example,
1->2->3->4->5 in the list, 5 should point to NULL. However if 5 points to 3 then it has a loop 3->4->5->3->4->5->3….

Answer: Take two pointers temp1 and temp2. Advance temp1 by one element at a time and temp2 by two elements at a time and keep doing this until temp1 / temp2 is null or temp1 and temp2 pointing to the same element. If it is later case then there is a loop, otherwise there is no loop/

The code for this is defined in the method DetectLoop in the page.

Leave a Reply

Your email address will not be published. Required fields are marked *