From 8b15ec147c2027f48f4d211d0f7e1c8c1d26d7c6 Mon Sep 17 00:00:00 2001 From: posper Date: Wed, 28 Jul 2021 14:21:34 +0800 Subject: [PATCH] =?UTF-8?q?141.=20=E7=8E=AF=E5=BD=A2=E9=93=BE=E8=A1=A8=20?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0141.环形链表.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/problems/0141.环形链表.md b/problems/0141.环形链表.md index 4a40f953..0871202d 100644 --- a/problems/0141.环形链表.md +++ b/problems/0141.环形链表.md @@ -14,7 +14,7 @@ 如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。 如果链表中存在环,则返回 true 。 否则,返回 false 。 -  + ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210727173600.png) # 思路 @@ -74,6 +74,21 @@ public: ## Java ```java +public class Solution { + public boolean hasCycle(ListNode head) { + ListNode fast = head; + ListNode slow = head; + // 空链表、单节点链表一定不会有环 + while (fast != null && fast.next != null) { + fast = fast.next.next; // 快指针,一次移动两步 + slow = slow.next; // 慢指针,一次移动一步 + if (fast == slow) { // 快慢指针相遇,表明有环 + return true; + } + } + return false; // 正常走到链表末尾,表明没有环 + } +} ``` ## Python