题目:
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?

解答:

/**
 * 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, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            //当slow与fast相遇的时候,fast比slow多了一圈,而slow也正好走了一圈。但是slow原来走的是圈外的路,从起点到圈开始的路,所以在实际圈里剩下的路程,其实就是从起点到圈开始的点的距离。那么我们设一个点slow2开始从起点走,走到slow2和slow相遇的时候,就是圈开始的点了
            if (slow == fast) {
                ListNode slow2 = head;
                while (slow2 != slow) {
                    slow2 = slow2.next;
                    slow = slow.next;
                }
                return slow;
            }
        }
        return null;
    }
}

guoluona
199 声望14 粉丝