From f3e576da31d909add5120985997373d100fce61a Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Tue, 18 Mar 2025 22:34:11 +0800 Subject: [PATCH] feat: 141_linked_list_cycle --- 141_linked_list_cycle/main.cpp | 38 ++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 141_linked_list_cycle/main.cpp diff --git a/141_linked_list_cycle/main.cpp b/141_linked_list_cycle/main.cpp new file mode 100644 index 0000000..9a091cb --- /dev/null +++ b/141_linked_list_cycle/main.cpp @@ -0,0 +1,38 @@ +#include +using namespace std; + +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { + public: + bool hasCycle(ListNode *head) { + if (!head) return false; + + ListNode *slowNode = head; + ListNode *fastNode = head->next; + + while (fastNode && fastNode->next) { + if (slowNode == fastNode && fastNode) { + return true; + } + + slowNode = slowNode->next; + fastNode = fastNode->next->next; + } + + return false; + } +}; + +int main() { + ListNode *head = new ListNode(1); + head->next = new ListNode(2); + + Solution().hasCycle(head); + + return 0; +}