Skip to content

Commit

Permalink
Create LoopDetection.java
Browse files Browse the repository at this point in the history
  • Loading branch information
harshithasudhakar authored Jan 16, 2025
1 parent 93e67a3 commit ca283e3
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions Linked List/Singly Linked List/LoopDetection.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/* Node is defined as
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
*/

class LoopDetection {
public static Node detectCycle(Node head){

Node meetingpoint = pointerMeet(head);
Node slow = meetingpoint;
Node fast = head;

while(fast!=slow){
fast = fast.next;
slow = slow.next;
}

return slow;
}
static Node pointerMeet(Node head){

Node slow = head;
Node fast = head;

while(fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return slow;
}
}
return null;
}
}

0 comments on commit ca283e3

Please sign in to comment.