Link list - floyd's cycle

#include
using namespace std;
class node{
public:
int data;
node* next;
node(int d){
data=d;
next=NULL;
}
};
int detectandremove(nodehead){
node
slow=head;
nodefast=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow){
remove(slow,head);
return 1;
}
}
return 0;
}
void remove(node
slow,nodehead){
node
ptr1;
node* ptr2;
ptr=head;
while(1){
ptr2=slow;
while (ptr2->next !=slow && ptr2->next != ptr1)
ptr2 = ptr2->next;
if (ptr2->next == ptr1)
break;
ptr1 = ptr1->next;
}

ptr2->next = NULL; 
  }

void printt(node*head){
while(head!=NULL){
cout<data<<"->";
head=head->next;
}
}

int main(){
node*head=new node(1);
head->next=new node(2);
head->next->next=new node(3);
head->next->next->next=new node(4);
head->next->next->next->next=new node(5);
head->next->next->next->next->next=new node(6);
head->next->next->next->next->next->next=new node(7);
head->next->next->next->next->next->next=head->next->next;
detectandremove(head);
printt(head);
}

whats wrong in this code

Hi @tishya_goyal

There were some minor mistakes. I have corrected them. Few of them are : don’t name a function which are already defined as keywords or have inbuilt function like remove. Also always declare the function to be used in other functions above them. Here, declare function remove above detectandremove. Also some other minor errors.
Link : https://ide.codingblocks.com/s/222541

Hope it Helps.

1 Like