my code is showing run time error what is the problem
Run time error in circular linked list
#include
using namespace std;
class node
{
public:
int data;
node* next;
//constructor
node(int d){
data=d;
next=NULL;
}
};
void insertAtTail(node*&head,int data){
if(head==NULL){
head=new node(data);
return;
}
node* temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=new node(data);
return;
}
void buildlist(node*& head){
int data;
cin>>data;
while(data!=-1)
{
insertAtTail(head,data);
cin>>data;
}
}
/int klast(nodehead,int k){
node* fast=head;
node* slow=head;
for(int i=1;i<=k;i++){
fast=fast->next;
}
while(fast!=NULL){
fast=fast->next;
slow=slow->next;
}
return slow->data;
}/
void print(node head){
node* temp=head;
while(temp!=NULL){
cout<data<<" ";
temp=temp->next;
}
}
void remove_cycle(node*&head){
node* slow=head;
node* fast=head;
slow=slow->next;
fast=fast->next->next;
while(slow!=fast){
slow=slow->next;
fast=fast->next;
}
slow=head;
while(slow!=fast){
slow=slow->next;
fast=fast->next;
}
while(fast->next!=slow){
fast=fast->next;
}
fast->next=NULL;
}
int main() {
node* head=NULL;
buildlist(head);
remove_cycle(head);
print(head);
return 0;
}
See in this question you have to first make loop in the linked list then call for remove cycle. Here in bulid function you have make the linked list as per the input like if we are given 1 2 3 4 5 2 3 -1 then in this case you have to make 5->next as 2 which is already present in the linked but in your code you are creating another node with value 2 and pointing 5->next to this new node so so are not forming any loop in the linked list this is why in remove cycle function when you keep on moving fast pointer forward then at one point of time it becomes NULL and when you try to access it next then it gives run time error. So you need to modify your build function in order to form a loop. Try to give it a thought and if you are still unable to get it then i will give you the code regarding this but first try it yourself.
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.