From 72a6b4ee41392c3d455f07c8e8805a2f55c11feb Mon Sep 17 00:00:00 2001 From: DearDeer7 <1479588900@qq.com> Date: Fri, 13 Nov 2020 00:00:28 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=90141.=20Linked=20List=20Cycle=E3=80=91?= =?UTF-8?q?=E3=80=90C++=E3=80=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 算法思维系列/双指针技巧.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/算法思维系列/双指针技巧.md b/算法思维系列/双指针技巧.md index f5edbd4..a939ea0 100644 --- a/算法思维系列/双指针技巧.md +++ b/算法思维系列/双指针技巧.md @@ -232,6 +232,28 @@ void reverse(int[] nums) { ======其他语言代码====== +[deardeer7](https://github.com/DearDeer7/) 提供 C++ 代码 +```cpp +class Solution { +public: + bool hasCycle(ListNode *head) { + // 链表为空或有一个元素,则无环 + if(!head || !head->next) return false; + + ListNode* slow = head; + ListNode* fast = head->next; + + while(fast && fast->next) { + fast = fast->next->next; + slow = slow->next; + // 快慢指针相遇,则有环 + if(fast == slow) return true; + } + return false; // 链表走完,快慢指针未相遇,则无环 + } +}; +``` + [ryandeng32](https://github.com/ryandeng32/) 提供 Python 代码 ```python class Solution: