题目描述

 

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Follow up:
Can you solve it without using extra space?

 

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null || head.next == null || head.next.next == null){
            return null;
        }
        ListNode fast = head.next.next;
        ListNode slow = head.next;
        while(fast != slow){
            if(fast.next == null || fast.next.next == null){//fast肯定比slow要快,一共有奇数个节点,fast.next == null则无环。一共有偶数个节点的时候,fast.next。next == null则无环
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        fast = head;
        while(fast != slow){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}