Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Please note that it's Function problem i.e.
- you need to write your solution in the form of Function(s) only.
- Driver Code to call/invoke your function is mentioned above.*/
- /*The structure of linked list is the following
- struct Node
- {
- int data;
- Node* next;
- };*/
- /*The function removes the loop from the linked list if present
- You are required to complete this method*/
- void removeTheLoop(Node *head){
- //Handling base cases
- if(head==NULL)return;
- if( (head->next)==head){
- head->next=NULL;
- return;
- }
- Node *slow=head,*fast=head->next;
- // Detecting cycle
- bool cycle=false;
- while(fast){
- slow=slow->next;
- if(fast->next==NULL)
- break;
- fast=fast->next->next;
- if(slow==fast){
- cycle=true;
- break;
- }
- }
- if(cycle){
- slow=head;
- while(slow!=(fast->next)->next){
- slow=slow->next;
- fast=fast->next->next;
- }
- //Bomb difused successfully
- fast->next->next=NULL;
- }
- }
Add Comment
Please, Sign In to add comment