**Description**Hints**Submissions**Solutions

Total Accepted: 112637 Total Submissions: 363331 Difficulty: Medium Contributor: LeetCode

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?

Hide Tags  Linked List Two Pointers Hide Similar Problems  (E) Linked List Cycle (M) Find the Duplicate Number

** 解题思路 ** 用快慢指针,快指针一次走两步,慢指针一次走一步,来先确定是否有cycle。
如果存在cycle,则将fast = head,再重新 fast =fast.next, slow = slow.next 两个指针都单步走,找到fast = slow点即可确定cycle起始点。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
 * 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 slow = head;
        ListNode fast = head;
        boolean isCycle = false;
        
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                isCycle = true;
                break; // don't forget to break the loop
            }
        }
        if (!isCycle) return null;
        
        // find the node while cycle begins
        fast = head;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        
        return slow;
    }
}