From c956e3cf18526ad8a3e5d2159ae805842b1909e7 Mon Sep 17 00:00:00 2001 From: zhengpj <17876253347@163.com> Date: Thu, 19 Nov 2020 15:37:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0141.LinkedListCycle=E7=9A=84J?= =?UTF-8?q?ava=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...07\351\222\210\346\212\200\345\267\247.md" | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\217\214\346\214\207\351\222\210\346\212\200\345\267\247.md" "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\217\214\346\214\207\351\222\210\346\212\200\345\267\247.md" index ff2aebe..522f51c 100644 --- "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\217\214\346\214\207\351\222\210\346\212\200\345\267\247.md" +++ "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\217\214\346\214\207\351\222\210\346\212\200\345\267\247.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; + } +} +``` + -- GitLab