From 2e9819611c399fb981288659909418583c9dadd3 Mon Sep 17 00:00:00 2001 From: jaredliw Date: Tue, 13 Jul 2021 21:06:03 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../链表篇/leetcode141环形链表.md | 26 ++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/animation-simulation/链表篇/leetcode141环形链表.md b/animation-simulation/链表篇/leetcode141环形链表.md index 2992b60..20c1ce8 100644 --- a/animation-simulation/链表篇/leetcode141环形链表.md +++ b/animation-simulation/链表篇/leetcode141环形链表.md @@ -10,7 +10,7 @@ #### 题目描述 -> 给定一个链表,判断链表中是否有环。pos代表环的入口,若为-1,则代表无环 +> 给定一个链表,判断链表中是否有环。pos代表环的入口,若为-1,则代表无环。 > > 如果链表中存在环,则返回 true 。 否则,返回 false 。 @@ -28,7 +28,7 @@ ![在这里插入图片描述](https://img-blog.csdnimg.cn/20210321132015849.png) -好啦,做题思路已经有了,让我们一起看一下代码的执行过程吧。\ +好啦,做题思路已经有了,让我们一起看一下代码的执行过程吧。 **动画模拟** @@ -42,7 +42,6 @@ Java Code: ```java public class Solution { public boolean hasCycle(ListNode head) { - ListNode fast = head; ListNode low = head; while (fast != null && fast.next != null) { @@ -80,11 +79,11 @@ class Solution { public: bool hasCycle(ListNode *head) { ListNode * fast = head; - ListNode * low = head; + ListNode * slow = head; while (fast != nullptr && fast->next != nullptr) { fast = fast->next->next; - low = low->next; - if (fast == low) { + slow = slow->next; + if (fast == slow) { return true; } } @@ -93,3 +92,18 @@ public: }; ``` +Python Code: + +```py +class Solution: + def hasCycle(self, head: ListNode) -> bool: + fast = head + slow = head + while fast and fast.next: + fast = fast.next.next + low = low.next + if fast == low: + return True + return False +``` +