diff --git a/141/141. shadowing b/141/141. shadowing new file mode 100644 index 0000000..80bedc1 --- /dev/null +++ b/141/141. shadowing @@ -0,0 +1,63 @@ +# Linked List Cycle +* 問題: https://leetcode.com/problems/linked-list-cycle/ +* 言語: C++ +* 参考: https://github.com/5103246/LeetCode_Arai60/pull/1/commits/c3cfb1bcf53a4329db7d6afdee8ecb37451860e6 + +```cpp +#include +#include + +struct ListNode { + int val; + ListNode* next; + ListNode(int x) : val(x), next(nullptr) {} +}; + +class Solution { + public: + bool hasCycle(ListNode *head) { + std::set reached; + ListNode* node = head; + while (node) { + if (reached.contains(node)) { + return true; + } + reached.insert(node); + node = node->next; + } + return false; + } +}; +``` + + +```cpp + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ + +class Solution { + public: + bool hasCycle(ListNode *head) { + ListNode* fast = head; + ListNode* slow = head; + while (fast != nullptr && fast->next != nullptr) { + if (fast->next != nullptr) { + fast = fast->next->next; + slow = slow->next; + if (fast == slow) { + return true; + } + } + } + return false; + } +}; + +```