# C++ Program to detect a loop in singly Linked List

Algorithm and the program for detecting any loop inside the singly Linked linked list is given below.
Implementation is simple we will use two pointer. We will increment one pointer by one the other one by two and then check if two pointers are equal or not. If they are equal then linked list has loop inside it otherwise linked list does not contain any loop.

ALGORITHM:
step 3:     doWhile current1!=NULL && current2!=NULL && current1->next!=NULL:
step 4:                   current1=current1->next
step 5:                   current2=current2->next->next
step 6:                   if(current1==current2):
step 7:                                return true
step 8:     endLoop
step 9:     return false

PROGRAM:

```#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

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

node* create_newnode(int data);

int main()
{

/*    Now we are creating the linked list shown below
with a loop i.e  node 16 is connected back to node 10

8--> 10--> 12--> 14--> 16
^                 |
|                 |
-------------------

*/

{
}
else
{
cout<<"\n\nLinked List does not contain loop in\n\n";
}

8--> 10--> 12--> 14--> 16-->NULL

The linked list shown above does not conatin any loop
*/

{
cout<<"\n\nLinked List has loop inside it!\n\n";
}
else
{
cout<<"\n\nLinked List does not has any loop insite it !\n\n";
}

}

node* create_newnode(int data)
{

struct node *newnode;
newnode=new node();
newnode->data=data;
newnode->next=NULL;
return newnode;

}

{

struct node *current1,*current2;
while(current1!=NULL && current2!=NULL && current2->next!=NULL)
{
current1=current1->next;
current2=current2->next->next;
if(current1==current2)
{
return true;
}
}
return false;
}```

OUTPUT: