LeetCode | Linked List Cycle II

https://leetcode.com/problems/linked-list-cycle-ii/

class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The node where the cycle begins. 
     *           if there is no cycle, return null
     */
    ListNode *detectCycle(ListNode *head) {
        if (!head) return head;
        
        ListNode *slow = head, *fast = head;
        bool isCycle = false;
        while (fast != NULL && fast->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
            if (fast == slow) {
                isCycle = true;
                break;
            }
        }
        
        if (!isCycle) return NULL;
        
        ListNode *u = head;
        while (u != slow) {
            u = u->next;
            slow = slow->next;
        }
        return u;
    }
};

参考:http://ihuafan.com/算法/floyds-cycle-finding-algorithm

原文地址:https://www.cnblogs.com/ilovezyg/p/6388432.html