Can anyone help me the code for the cycle removal?
Code for cycle removal
void cycleremoval(nodehead){ nodeslow=head; nodefast=head; while(fast!=NULL && fast->next!=NULL){ fast=fast->next->next; slow=slow->next; if(fast==slow){ slow=head; while(slow!=fast){ nodetemp; temp=fast; fast=fast->next; slow=slow->next; } temp->next=NULL; } } }
Is the code correct?
logic is correct but this is not correct way to implement this
as in the very first iteration head==fast
correct way:
void BreakCycle(node*head){
node*slow=head,*fast=head->next,*temp=NULL;
while(fast&&fast->next){
if(slow==fast)break;
slow=slow->next;
fast=fast->next->next;
}
// if cycle not present
if(fast==NULL||fast->next==NULL)return;
/// now count no of nodes in loop
int k=1;
slow=slow->next;
while(slow!=fast){
k++;
slow=slow->next;
}
// now point slow to head and fast to k node ahead
slow=head;
fast=head;
while(k--){
fast=fast->next;
}
/// move slow and fast one by one
while(slow!=fast){
slow=slow->next;
fast=fast->next;
}
// now move only fast
while(fast->next!=slow){
fast=fast->next;
}
fast->next=NULL;
}
this is right way to implement the code
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.