Spread the post

Find or Detect loop in a linked list

Suppose following data are inserting in linked list.

Detect loop

View insertion at beginning.

Try it yourself

Algorithm:

Use two pointer first_ptr and second_ptr. both are point to root (head) of linked list. And increment first pointer first_ptr by 2 and second_ptr by one if first_ptr are equal to second_ptr. That means loop are exist. Otherwise not.

Code execution:

Stack Areamainroot(pointer)detect_loopsfirst_ptr(pointer)second_ptr(pointer) Heap Areastruct Nodedata (int)= 1next (pointer) struct Nodedata (int)= 2next (pointer) struct Nodedata (int)= 3next (pointer) struct Nodedata (int)= 4next (pointer) struct Nodedata (int)= 5next (pointer) struct Nodedata (int)= 6next (pointer) struct Nodedata (int)= 7next (pointer) struct Nodedata (int)= 8next (pointer)

Note that not given all step of execution process here.View How to insert linked list element and so on.

Try it yourself

C program to find and detect loop of given linked list.

OutPut:

Spread the post