// https://leetcode.com/problems/linked-list-cycle/ /** * Definition for singly-linked list. */ #include struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; // Pursuing the cheeky logic from last time, indeed, we can run the loop 10001 times, // and if the pointer still isn't at the end, we know it must be stuck in a loop // (since the longest possible list is only 10000). // This actually performs surprisingly well on the leaderboard, despite being totally, totally // overkill for almost all the cases :) class Solution { public: bool hasCycle(ListNode *head) { ListNode* ptr = head; for (int i = 0; i < 10001; i++) { if (ptr == nullptr) { return false; } ptr = ptr->next; } return true; } };