Double Pointers
Break loop
void dectectAndRemoveLoop(Node node){
// if list is empty or has only one node
if (node == null){
return;
}
Node slow = node, fast = node;
// search for loop
while (fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if (fast == slow){
// search connected node and remove the loop
slow = node;
while(slow.next != fast.next){
slow = slow.next;
fast = fast.next;
}
fast.next = null;
break;
}
}
}287. Find the Duplicate Number
61 Rotate List
138 Copy List with random pointer
Last updated