Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
思路:
这道题的难点在于返回cycle begins,我们之前用快慢指针能够确认他是否有cycle,但是如何返回初始点呢?网上找到了一个比较容易理解的解释:
When fast and slow meet at point p, the length they have run are ‘a+2b+c’ and ‘a+b’.
Since the fast is 2 times faster than the slow. So a+2b+c == 2(a+b), then we get ‘a==c’.

/**
* 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) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
ListNode real = head;
while(real != slow){
real =real.next;
slow = slow.next;
}
return real;
}
}
return null;
}
}
本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:
评论列表(1条)
[…] 要理解这道题,先要理解题目142:https://blog.jing.do/5371。 […]