-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution142.java
48 lines (40 loc) · 912 Bytes
/
Solution142.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
39
40
41
42
43
44
45
46
47
48
package algorithm.leetcode;
/**
* @author: mayuan
* @desc: 环形链表 II
* @date: 2019/01/04
*/
public class Solution142 {
public ListNode detectCycle(ListNode head) {
if (null == head) {
return null;
}
boolean isCycle = false;
ListNode slow = head, fast = head;
while (null != fast && null != fast.next) {
fast = fast.next.next;
slow = slow.next;
if (slow == fast) {
isCycle = true;
break;
}
}
if (!isCycle) {
return null;
}
fast = head;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
}