Answers for "remove loop from linked list"

0

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;
}
}
}
Posted by: Guest on September-29-2020

Browse Popular Code Answers by Language