#include #include struct ListNode { int val; std::shared_ptr next; ListNode(int x) : val(x), next(nullptr) {} }; bool hasCycle(std::shared_ptr head) { auto slow = head; auto fast = head; while (fast != nullptr && fast->next != nullptr) { slow = slow->next; fast = fast->next->next; if (slow == fast) { return true; } } return false; } int main() { auto head = std::make_shared(1); head->next = std::make_shared(2); head->next->next = std::make_shared(3); head->next->next->next = std::make_shared(4); head->next->next->next->next = head->next; std::cout << hasCycle(head) << std::endl; // Output: 1 (true) return 0; }