-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
35 lines (31 loc) · 850 Bytes
/
Solution.java
File metadata and controls
35 lines (31 loc) · 850 Bytes
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
package leetCode_142;
/**
* @author dimdark
* @date 2017-09-09
* @time 10:59 AM
*/
public class Solution {
static class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) return null;
ListNode fast = head, slow = head, entry = head;
while (fast.next != null && fast.next.next != null) { // non-cycle if not true
slow = slow.next;
fast = fast.next.next;
if (fast == slow) { // encounter
while (entry != slow) {
entry = entry.next;
slow = slow.next;
}
return entry;
}
}
return null; // non-cycle
}
}