LeetCode——142. Linked List Cycle II

题目:

/**
 * 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) {
        auto slow = head, fast = head;
        auto hasLoop = false;
        if (slow == nullptr) {
            return nullptr;
        }
        while(fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) {
                hasLoop = true;
                break;
            }
        }
        if (hasLoop == false) {
            return nullptr;
        }
        slow = head;
        while(fast != slow) {
            slow = slow->next;
            fast = fast->next;
        }
        return slow;
    }
};
posted @ 2020-10-12 10:13  夜溅樱  阅读(36)  评论(0编辑  收藏  举报