题目

linked-list-cycle


算法

* 快慢指针


代码

* 快慢指针

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *slow = head, *fast = slow;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) break;
        }
        if (!fast || !fast->next) return false;
        return true;
    }
};

results matching ""

    No results matching ""