142. Linked List Cycle II [leecode]

 利用 floyd cycle detection原理来解题

分析详见 博客287. Find the Duplicate Number [Leetcode]


代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if (!head || !head->next) return NULL;
        ListNode * slow = head->next, * fast = head->next->next;
        while (slow != fast) {
            if (!fast || !fast->next) return NULL;
            slow = slow->next;
            fast = fast->next->next;
        }
        fast = head;
        while (fast != slow) {
            fast = fast->next;
            slow = slow->next;
        }
        return fast;
        
    }
};


你可能感兴趣的:(leetcode,floyd,cycle,链表,算法,leetcode)