原题链接在这里:https://leetcode.com/problems/linked-list-cycle-ii/
首先找到是否有cycle,若是没有返回null。
若是有cycle,可以从head,用two pointers一个一个试直到找到cycle beginner,Time O(n^2).
另外一种方法参见了这篇帖子,是数学想法。
AC Java:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null){
return null;
}
ListNode walker = head;
ListNode runner = head;
while(runner!=null && runner.next!=null){
walker = walker.next;
runner = runner.next.next;
if(walker == runner){
walker = head;
while(walker != runner){
walker = walker.next;
runner = runner.next;
}
return runner;
}
}
return null;
}
}