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