LeetCode: Linked List Cycle II

LeetCode: Linked List Cycle II

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

/**
* Description
*
* @author hzhou
*/
public class LinkedListCycleII {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode fast = head.next.next;
ListNode slow = head.next;
while (fast != null && fast != slow) {
slow = slow.next;
fast = fast.next != null ? fast.next.next : null;
}
if (fast == null) {
return null;
}
fast = head;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return fast;
}
}