[leetcode]Linked List Cycle II

http://oj.leetcode.com/problems/linked-list-cycle-ii/

老题。当快慢指针相交时,通过方程或观察可知,从head到环开始点的距离和从相遇点开始是一样的,那么从相遇点和从开始点再一起走直到相遇就行了。

/**

 * 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) {

        ListNode *fast = head;

        ListNode *slow = head;

        do {

            if (fast == NULL || fast->next == NULL) return NULL;

            fast = fast->next->next;

            slow = slow->next;

        } while (fast != slow);

        ListNode *n1 = head;

        ListNode *n2 = slow;

        while (n1 != n2) {

            n1 = n1->next;

            n2 = n2->next;

        }

        return n1;

    }

};

 

你可能感兴趣的:(LeetCode)