Skip to content

Commit ca283e3

Browse files
Create LoopDetection.java
1 parent 93e67a3 commit ca283e3

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/* Node is defined as
2+
3+
class Node
4+
{
5+
int data;
6+
Node next;
7+
Node(int d) {data = d; next = null; }
8+
}
9+
10+
*/
11+
12+
class LoopDetection {
13+
public static Node detectCycle(Node head){
14+
15+
Node meetingpoint = pointerMeet(head);
16+
Node slow = meetingpoint;
17+
Node fast = head;
18+
19+
while(fast!=slow){
20+
fast = fast.next;
21+
slow = slow.next;
22+
}
23+
24+
return slow;
25+
}
26+
static Node pointerMeet(Node head){
27+
28+
Node slow = head;
29+
Node fast = head;
30+
31+
while(fast!=null && fast.next!=null){
32+
slow = slow.next;
33+
fast = fast.next.next;
34+
if(slow == fast){
35+
return slow;
36+
}
37+
}
38+
return null;
39+
}
40+
}

0 commit comments

Comments
 (0)