Question:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Analysis:
只想到了,首先判断是否有环,若有环,则总链首开始,一次判断是否是环的开始,这样T(O) = O(n^2)。
其实是一个数学问题,详细思路参照链接http://blog.csdn.net/sbitswc/article/details/27584037 。
Answer:
public ListNode detectCycle(ListNode head) {
ListNode fast = head, slow = head;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if(fast == slow)
break;
}
if(fast == null || fast.next == null)
return null;
slow = head;
while(fast != slow) {
fast = fast.next;
slow = slow.next;
}
return fast;
}
LeetCode -- Linked List Circle ii
原文:http://www.cnblogs.com/little-YTMM/p/4803631.html