Bloomberg Interview Question

Is there any algorithm to verify whether a linked list is circular or not?

Interview Answers

Anonymous

Jan 22, 2014

We maintain two pointers initialized to the head of the Linked list. Name the two pointers as slow and fast. Slow pointer is advanced once at each step and the faster pointer is advanced twice at each step. If the two pointers meets i.e. points to the same node in the list at some point of time, there is a loop in the list or else if the fast pointer reaches the end of list without overlapping with the slow pointer, then the Linked list is loop free.

2

Anonymous

Jan 16, 2014

Start from the head of the Linked List. Store this head in a reference (in Java) or pointer (in C, C++). At every node check if next is pointing to the same location as that of the temporary reference or pointer of the head. If yes, stop and declare "Circular". Else if the next is null, stop and declare "Not Circular". Else if next is not same as head and is not null, repeat the same process on that next node.