Please optimize my code wherever possible for loop removal

#include
using namespace std;

class node{

public:
int data;
node* next;

//constructor
node(int d){
data=d;
next =NULL;
}

};

nodetemp3;
node
temp7;

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;

}

hi @himanshuanand729 u can refer

you used a while loop inside a while loop i thought of this method but used flag in order to not use while loop will your method not increase time complexity or is it not depending on n and doing similar amount of work…hence taking same time.

hi @himanshuanand729 time complexity will be anyhow O(length of chain) even if u write break statement as u are anyhow travelling the entire list