题目描述:
这一部分在链表那篇讲环的部分也有讲到具体的数学特点和做法,直接上coding:
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null || head.next.next==null){
return null;
}
if (head.next==head){
return head;
}
ListNode f = head.next.next,s = head.next;
while (f!=s){
if (f.next==null||f.next.next==null){
return null;
}
f = f.next.next;
s = s.next;
if (f == s){
f = head;
while (f!=s){
f = f.next;
s = s.next;
}
return f;
}
}
return null;
}
}