How to check whether a linked list is circular?

 How to check whether a linked list is circular?

Create two pointers, and set both to the start of the list. Update them as increment first pointer by one and second pointer by two if its a circular link list they will defenitely meet at some point

Below is a sample program to check circular link list:-

while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next;
if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print ("circular");
}}

No comments:

 
Top Blogs