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;
}
}
微信扫一扫
支付宝扫一扫
评论列表(1)