You are given a linked list of N nodes. Remove the loop from the linked list, if present. Note: X is the position of the node to which the last node is connected to. If it is 0, then there is no loop. code example

Example: remove loop from linked list

//java 

Node remove(Node head){
//detect the loop
Node slow=head;
Node fast=head;
while(slow!=null&&fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast){
if(slow==head){
while(slow.next!=head){
slow=slow.next;
}
slow.next=null;
}
if(slow==fast){
slow=head;
while(slow.next!=fast.next){
if(slow==fast.next){
fast.next=null;
}
slow=slow.next;
fast=fast.next;
}
fast.next=null;
}
}
}

Tags:

C Example