Given a linked list of N nodes. The task is to check if the the linked list has a loop. Linked list can contain self loops. leetcode 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;
}
}
}