-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.java
38 lines (34 loc) · 908 Bytes
/
solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
//Floyd's Cycle Detection
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
//Two pointer meet so cycle detected
if(slow == fast){
//Find start of the cycle
slow = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return fast;
}
}
//No cycle was there
return null;
}
}