#include
using namespace std;
class node{
public:
int data;
node* next;
//constructor
node(int d){
data=d;
next =NULL;
}
};
nodetemp3;
nodetemp7;
void print(node* head)
{
while(head!=NULL)
{
cout<<head->data<<"->";
head=head->next;
}
}
bool detectCycle(nodehead)
{
node slow=head;
node* fast=head;
while(fast!=NULL && fast->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
{
return true;
}
}
return false;
}
void loopremoval(node* &head)
{
if(!(detectCycle(head)))
{
return ;
}
node* slow=head;
node* fast=head;
node* prev=head;
int flag=0;
while(fast!=NULL && fast->next!=NULL)
{
if(flag==0)
{
fast=fast->next->next;
slow=slow->next;
}
if(flag==1)
{
prev=prev->next;
fast=fast->next;
slow=slow->next;
}
if(fast==slow)
{
flag++;
if(flag==1)
{
slow=head;
prev=fast;
fast=fast->next;
slow=slow->next;
}
if(flag==2)
{
prev->next=NULL;
break;
}
}
}
}
int main()
{
node* head;
head->data=1;
node*temp=head;
for(int i=2;i<8;i++)
{
temp->next=new node(i);
temp=temp->next;
//cout<data<<endl;
if(i==3)
{
//cout<<“dnn”<<endl;
temp3=temp;
//cout<data<<endl;
}
//cout<data<<endl;
if(i==7)
{
temp7=temp;
cout<data<<endl;
}
//cout<data<<endl;
}
print(head);
cout<<endl;
//cout<data;
//cout<data<<endl;
temp7->next=temp3;
loopremoval (head);
print(head);
return 0;
}