LeetCode142-环形链表II

LeetCode142-环形链表II

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public ListNode detectCycle(ListNode head) {
ListNode fast = head, snow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
snow = snow.next;
//两指针相遇了
if (snow == fast) break;
}
if (fast == null || fast.next == null) {
// fast 遇到空指针说明没有环
return null;
}
//否则有环
//将慢指针从头结点重新开始走
snow = head;
while (snow != fast) {
snow = snow.next;
fast = fast.next;
}
return snow;
}