-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_142.java
More file actions
28 lines (25 loc) · 701 Bytes
/
Copy pathP_142.java
File metadata and controls
28 lines (25 loc) · 701 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
package leetcode.medium;
import utils.DataStructures.ListNode;
@SuppressWarnings({ "ReturnOfNull", "ConstantConditions" })
public class P_142 {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
do {
slow = slow.next;
fast = fast.next.next;
} while (slow != fast && fast != null && fast.next != null);
if (fast != slow) {
return null;
}
fast = head;
while (fast != slow) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}