# Write a program function to detect loop in a linked list

Given a linked list, check if the the linked list has loop or not. Below diagram shows a linked list with a loop.

Following are different ways of doing this
Use Hashing:
Traverse the list one by one and keep putting the node addresses in a Hash Table. At any point, if NULL is reached then return false and if next of current node points to any of the previously stored nodes in Hash then return true.

Mark Visited Nodes:
This solution requires modifications to basic linked list data structure.  Have a visited flag with each node.  Traverse the linked list and keep marking visited nodes.  If you see a visited node again then there is a loop. This solution works in O(n) but requires additional information with each node.
A variation of this solution that doesn’t require modification to basic data structure can be implemented using hash.  Just store the addresses of visited nodes in a hash and if you see an address that already exists in hash then there is a loop.

Floyd’s Cycle-Finding Algorithm:
This is the fastest method. Traverse linked list using two pointers.  Move one pointer by one and other pointer by two.  If these pointers meet at some node then there is a loop.  If pointers do not meet then linked list doesn’t have loop.

Implementation of Floyd’s Cycle-Finding Algorithm:

## C/C++

```// C program to detect loop in a linked list
#include<stdio.h>
#include<stdlib.h>

struct node
{
int data;
struct node* next;
};

void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));

/* put in the data  */
new_node->data  = new_data;

/* link the old list off the new node */

/* move the head to point to the new node */
}

int detectloop(struct node *list)
{
struct node  *slow_p = list, *fast_p = list;

while (slow_p && fast_p && fast_p->next )
{
slow_p = slow_p->next;
fast_p  = fast_p->next->next;
if (slow_p == fast_p)
{
printf("Found Loop");
return 1;
}
}
return 0;
}

/* Drier program to test above function*/
int main()
{

/* Create a loop for testing */

return 0;
}
```

## Java

```// Java program to detect loop in a linked list
{

class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}

/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);

/* 3. Make next of new Node as head */

/* 4. Move the head to point to new Node */
}

int detectLoop()
{
while (slow_p != null && fast_p != null && fast_p.next != null) {
slow_p = slow_p.next;
fast_p = fast_p.next.next;
if (slow_p == fast_p) {
System.out.println("Found loop");
return 1;
}
}
return 0;
}

/* Drier program to test above functions */
public static void main(String args[])
{

llist.push(20);
llist.push(4);
llist.push(15);
llist.push(10);

/*Create loop for testing */

llist.detectLoop();
}
}
/* This code is contributed by Rajat Mishra. */
```

## Python

```
# Python program to detect loop in the linked list

# Node class
class Node:

# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None

def __init__(self):

# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)

def printList(self):
while(temp):
print temp.data,
temp = temp.next

def detectLoop(self):
while(slow_p and fast_p and fast_p.next):
slow_p = slow_p.next
fast_p = fast_p.next.next
if slow_p == fast_p:
print "Found Loop"
return

# Driver program for testing
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(10)

# Create a loop for testing
llist.detectLoop()

# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

```

Output:
`Found loop`

Time Complexity: O(n)
Auxiliary Space: O(1)

# Company Wise Coding Practice    Topic Wise Coding Practice

• sumit agarwal

how is the Floyd’s cycle-finding algorithm fastest??? according to me it’s complexity is more than O(n) something like O(a*n) where a>1

• sangee

Can someone explain how dis happens?..how do the tortoise and hare eventually meet up?

• SANTOSH KUMAR MISHRA

{
node *slowptr,*fastptr;
{
printf(“nnList is empty.”);
return FALSE;
}
while(slowptr && fastptr && fastptr->next)
{
fastptr = fastptr->next->next;
slowptr = slowptr->next;
if(slowptr == fastptr)
return TRUE;
}
return FALSE;
}

• ALEX

we moves fast pointer by 2………

Here the reason…..

what if we want to print that node value, or if we want to find on which node we are having loop….?????

ANS:

step1: Firstly find the loop in the linked list using fast pointer and slow pointer.

step2: set the slow point on head.

step3: now move fast pointer and slow pointer by one skip.

step4: slow_pointer and fast_pointer will meet at that node on which loop is occur……….

you can take any example and check it…

Correct me if i’m wrong…..

• Suyash Soni

What does that condition inside while loop while(slow_p && fast_p && fast_p->next ) mean? Please tell me that when will this loop stop?

• walter white

if there is no loop , we get at some point slow_p or fast_p = NULL, to move out of while loop

• tharun

Divide the problems into 3 cases :

Even number of nodes[fast!=NULL]
Odd number nodes[fast->next!=NULL]
Only one node[slow!=NULL]

• Kevin Alex Mathews

I think we can use Depth First Search graph for the problem. In the DFS spanning tree, if there is any back edge, then that points to the presence of loop in the linked list.

Time complexity of O(n+e) is comparable to Floyd’s cycle detection algorithm’s O(n), where n is the number of nodes in the list and e is the number of pointers.

• v3gA

That’s the same as marking the node as visited. (2nd method)

• Himanshu Dagar

I think that there is no need of checking slow_p condition in the while loop
(It will even work without this condition)

• Himanshu Dagar

Floyd’s Cycle Finding algorithm
(we can not remove that loop from the linked list with the help of this algo.)

• neelabhsingh

suppose there is node which pointing to itself then is there is loop or not. Obviously this node is last node in the linked list. Instead point to NULL it is pointing to itself ? Please clear it..

• swebdev

Ofcourse there is loop.. The double pointer and single-pointer will point to same node at the beginning and also after one unit of movement, thus they will point to same node, returning true.

• ABHILASHA31

{
node *p,*q;
while(q!=NULL)
{
if(q->next==q)
flag=1;
else
{
while(p!=q)
{
{
if(p!=q->next)
p=p->next;
else
flag=1;
}
}
}
q=q->next;

}
if(flag==1)
{
q->next=NULL;
}

}}

wats wrng wid d abv piece f code. emcompasses bth detection nd removal

• Karshit

My code for Cycle detection and Removal…
HOpe you guys find it useful.

#include <iostream>

using namespace std;

struct node {
int data;
node *next;
};

{
cout << head -> data << " ";
}

}

{
bool flag = false;

while (slow && fast && fast -> next) {
slow = slow -> next;
fast = fast -> next -> next;

if (slow == fast) {
flag = true;
cout << "Cycle Detected…..\nRemoval in Progress\n";
break;
}
}

if (!flag) // no cycle
return;

/*procedure for removal of loop*/
fast = fast -> next;
int a = 0;

while (fast != slow) { // a = number of nodes in loop
a++;
fast = fast -> next;
}

for (int i = 0; i <= a; i++) {
slow = slow -> next;
}

slow -> next = NULL;
}

int main()
{

/*making a linklist with a loop*/
head1 -> next = new node();

head1 -> next = new node();
head1 -> next = new node();
head1 -> next = new node();

cout << "\n";

return 0;
}

• its_dark

sorting takes O(nlogn). We are doing here in O(n)

• Vibhu Tiwari

I think a loop in a linked list can just be determined by first sorting the linked list and then determining if any node’s value is less than the previous one.If yes then there is a loop in a linked list.

What will be your terminating condition when you are sorting the list?

• mayank199317

{
{

{
return 1;
else
temp=temp->next;
}

return (1);

}
return 0;
}

Thank you.

• Vicky

1st method which is use Hashing:

How I can implement hashtable in c?
Is there is any article regarding this on geeksandgeeks?

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```
• Have a look at this:: http://ideone.com/Hl2xat ..

• Animesh Pratap Singh

here is simple explanation….

``` ```
{
while(slow!=fast)
{
slow=slow->next;
fast=fast->next->next;
printf("%d ",fast->info);
}
fast=fast->next;
while(c!=fast)
{
while(slow!=fast)
{
if(c==fast->next)
{
fast->next=NULL;
return;
}
fast=fast->next;
}
c=c->next;
fast=fast->next;
}

}

int main()
{
while(mover->next!=NULL)
{
mover=mover->next;
}
return 0;
}

``` ```
• learner

Why are we checking the condition for fast_p->next ?
We are moving the fast pointer 2 hops at a time. Hence a check for fast_p->next->next is the one that is needed right. Please enlighten me.

• suppose you are on the last node and there is no loop in the original list….the statement “fast_p->next->next” can lead to a segmentation fault…since the next of last is NULL and there is no next to NULL.
this is why the condition check is necessary.

• candis

why do we always have fast pointer moving only twice faster than the slow pointer…..what if we move it with thrice the speed….they will meet even then too…
plz check me if I m wrong with an example….

• Aparna

What is the point of that? If anything, it will make more passes in the loop until it meets the first pointer.

• Gaurav pruthi

Exactly +1.

• Yes, we can make the pointer to skip by arbitrary number of positions. It is not guaranteed that loop will always present. Note that if you hop by k nodes, you need k checks to ensure the intermediate nodes are not null in the while loop (in case if there is no loop).

More over, quantitatively it is more interesting to see at what node these slow and fast pointers meet, given that there are M nodes in loop, fast pointer hops by K nodes in every iteration and the fast pointer offset by F nodes by that time slow pointer enters into the loop.

Try it… check benefits, what should be optimal value of K (hopping length) based on inputs M and F.

It is somewhat related to wheel rotations in mechanical systems :).

• ALEX

we moves fast pointer by 2………
Here the reason…..

what if we want to print that node value, or if we want to find on which node we are having loop….?????
ANS:
step1: Firstly find the loop in the linked list using fast pointer and slow pointer.
step2: set the slow point on head.
step3: now move fast pointer and slow pointer by one skip.
step4: slow_pointer and fast_pointer will meet at that node on which loop is occur…..
you can take any example and check it…

Correct me if i’m wrong…..

• abc

A faster code using Brent’s algorithm would be:

``` ```
{
return false;
int i = 0;
int k = 1;

while (slow != NULL)
{
slow = slow->next;
i++;
if (slow == fast)
return true;
if (i == k)
{
fast = slow;
k*= 2;
}
}
return false;
}
``` ```
• Algoseekar

@abc hi can u explain whats the brent algo..in wiki it saying that we ahve tp find smallest power of 2 that is greater then both u,lembda can u explain what is the U &m lembda in floyed cycle algo & brent algo are..?? plz help

Thanks
Algoseekar

• Algoseekar

@abc an u explain whats the brent algo..in wiki it saying that we ahve tp find smallest power of 2 that is greater then both u,lembda can u explain what is the U &m lembda in floyed cycle algo & brent algo are..?? plz help

Thanks
Algoseekar

• ska

lambda = length of the cycle;
mu = length of extra nodes before the cycle begins.
If i is the total distance traveled,
length of the linked list = lambda + mu
Clearly the two pointers can only meet if the traveled distance i > mu. Now in this particular algorithm, since we move the slower pointer to the faster pointer’s location directly, once when the slower pointer is inside the loop, the faster pointer can catch up with it only if the smallest power of 2 is greater than the loop length lambda. If that is not the case, then we move the slower pointer to the faster pointer’s location and increase the power of 2.
The above code is slightly confusing because we are moving the slow pointer instead of the fast. It might also not completely comply with the Brent’s algorithm given on wiki, and might take more powers of two because we need to make i=0 each time the condition i==k gets satisfied.
Note: If i is made zero each time, then i = lambda by the end of the function.

• maverick

how can we find out the starting position of the loop?

• vinit

first find the length of the loop.
traverse the list from head by count elements. lets say it is pointing in between somewhr ptr p.
again start traversing from head as well as from ptr p. where ever they’ll meet, that is the starting point of the loop.

Correct me if i m wrong.

• cyber

I was wondering if this would work too.. take two pointers and run one at speed one and the other at twice the speed. So eventually they will meet and loop would be detected ! ?

please correct me if am wrong

• cyber

ohh..sorry for that..wrote that comment before even reading/analysing the code.. And I didn’t know that is named as Flyod’s algo..

thanks

• wav
``` ```
while(slow_p && fast_p &&
slow_p->next &&------->why r we doing this
fast_p->next &&
fast_p->next->next )

why r we checking so many conditions..

shouldn't it be
while(slow_p&&fast_p &&fast_p->next&&fast_p->next->next) only
``` ```
• vipulkv

Yes this condition will suffice.
Basically fast pointer would always have traversed the node which slow pointer is going to traverse.

• Vamsi

I think much simpler would be

``` ```
fP = list;
while( !fP && !fP->next ) {
if ( (list = list->next) == (fP=fP->next->next))
return TRUE;
}
return FALSE;``` ```
• GeeksforGeeks

@wav, @vipulkv and @vamsi: Thanks for providng the inputs, we have updated the post and removed unnecessary conditions.

• martin

@geeksforgeeks..can you please post the Brent algorithm of cycle detection thats also good one

• Shubham Saxena

what if we have more than 1 loop in a linked list?

• Brent’s Algorithm is much better than Floyd’s Algorithm and equally simple to implement.

• here is The Code to Detect & remove the loop from The Linked List..Hope GeeksForGeeks Will Include it in original Post

``` ```

#include<stdio.h>
#include<stdlib.h>

struct Node
{
int value;
struct Node* next;
};

void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));

/* put in the data  */
new_node->value= new_data;

/* link the old list off the new node */

/* move the head to point to the new node */
}

{

struct Node *p1 = NULL, *p2 = NULL;

{
if (p1 == NULL && p2 == NULL)
{
// 1. Two pointers start from head

}
else
{
// 2 If two pointers meet, there is a loop

if (p1 == p2)
break;
}

// 3 If pointer reachs the end, there is no loop
if (p2->next == NULL || p2->next->next == NULL)
{
printf("There is no loop in the list.\n");
return ;
}

p1 = p1->next;
p2 = p2->next->next;
}

// 5. Find out how many nodes in the loop, say k.

unsigned int k = 1;
p2 = p2->next;
while (p1 != p2)
{
p2 = p2->next;
k++;
}
printf("There are %d nodes in the loop of the list.\n", k);

// 6. Reset one pointer to the head, and the other pointer to head + k.

for (unsigned int i = 0; i next;

// 7. Move both pointers at the same pace, they will meet at loop starting node
while(p1 != p2)
{
p1 = p1->next;
p2 = p2->next;
}

printf("node %d is the loop starting node.\n", p1->value);

// 8. Move one of the pointer till its next node is the loop starting node.
// It's the loop ending node
p2 = p2->next;
while(p2->next != p1)
p2 = p2->next;

printf("node %d is the loop ending node.\n", p2->value);
// 9. Set the next node of the loop ending node to fix the loop
p2->next = NULL;

}

/* Utility function to print a linked list */
{
{
}
printf("\n");
}

int main()
{

printf("\n");
}

``` ```
• @Shashank, nice work.

• Guduru Sivareddy

@shashank best and simple solution I have ever seen.

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```
• nilayan_ahmed

fast_p->next->next will crash if fast_p->next is NULL and fast_p->next is NULL for the last node hence the check.