---
title: "Linked List Cycle II"
author: "KickCode"
date: "2016-02-14T02:41:06Z"
tags: []
categories: ["编程语言"]
slug: "linked-list-cycle-ii"
draft: false
lastmod: "2016-02-14T02:47:12Z"
id: 2276311
url: "https://kickcode.iteye.com/blog/2276311"
---

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?

![](http://dl2.iteye.com/upload/attachment/0115/0680/e660c150-2f28-3b2c-bc19-5ae8044e9d80.png)
判断一个链表中是否有环存在，并且输出环的起始点。我们用快慢指针fast，slow来判断是否有环存在，如果它们可以相遇就说明有环存在，如果不能相遇说明没有环存在。它们相遇之后，图中的meet点是它们的相遇点，假设join为环的起始点，我们假设head到join的距离为a, join到meet的距离为b(逆时针)，meet到join的距离为c(逆时针)。如果它们相遇，那么fast走过的路程是slow走过的两倍，所以a + b + c + b = 2 ( a + b)，即a = c。有了这个关系我们只需要用两个指针一个从相遇点出发，另一个从头结点出发，它们相遇的点就是环的起始点。代码如下：

```java

/**
 * 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 && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast) 
                break;
        }
        if(fast != slow) return null;
        fast = head;
        while(fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}

```