Posted on by Kalkicode
Code Single linked list

Find length of loop in linked list

Linked list is element of nodes, Suppose given linked list are contain loops. That means last node of linked list is not NULL. And our goal is to detect loop length how many number of nodes are involved. That is interesting and commonly asked question in linked list programming. In this post we are discussing about how to solve this problem in effective manner.

First see the situation of loop in linked list. Suppose we are inserted the following (1,2,3,4,5,6,7,8) node in a sequence. And last node of this linked list are store the reference of other node of linked list.

Length of Loop in linked list

In this example last node is connected to 3rd node of linked list. And this is create a loop when we iterates this linked list. We can solve this problem in following way.

Process: 1) First our goal is detect loop in linked list. So we are need to iterate linked list nodes element. We are use two pointer variables first and second.

Here given code implementation process. And assign the address of head node to both pointers.

2) 2) In this case second pointer variable are visited every second upcoming nodes. that means this variable logical increment by two. and as respect to first pointer are visiting next node.

3) Repeat step 2 process until there are first and second pointer are not hold same node address. So finally we get nodes which part of loop nodes. Then do step 4.

4) Step 3 we are get node which is part of loops. Finally iterating linked list by using of this get node. This iteration is similar to circular linked list.

Here mentioned solution in all modern languages.


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment