diff --git a/算法思维系列/双指针技巧.md b/算法思维系列/双指针技巧.md index ff2aebe..522f51c 100644 --- a/算法思维系列/双指针技巧.md +++ b/算法思维系列/双指针技巧.md @@ -257,3 +257,26 @@ class Solution: # 退出循环,则链表有结束,不可能为环形 return False ``` + +[zhengpj95](https://github.com/zhengpj95) 提供 Java 代码 + +```java +public class Solution { + public boolean hasCycle(ListNode head) { + //链表为空或只有一个结点,无环 + if (head == null || head.next == null) return false; + + ListNode fast = head, slow = head; + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + // 快慢指针相遇则表示有环 + if (fast == slow) return true; + } + + //fast指针到末尾,无环 + return false; + } +} +``` +