题目分析
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?
推导过程:
s = x + ny + k
f = x + my + k
f = 2s
(m - 2n)y - x = k
(m-2n)y = k + x
(m-2n)y 正好等于整数倍的环
对应从第 k 个位置走 x 步正好到环的起点
代码
/**
* 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 fast = head;
ListNode slow = head;
while(fast != null && slow != null) {
fast = fast.next;
slow = slow.next;
if(fast != null) {
fast = fast.next;
}
if(fast == slow) {
break;
}
}
if(fast == null) {
return null;
}
fast = head;
while(fast != slow) {
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
网友评论