添加141.LinkedListCycle的Java解法

This commit is contained in:
zhengpj
2020-11-19 15:37:17 +08:00
committed by GitHub
parent 0b2efdc765
commit c956e3cf18

View File

@ -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;
}
}
```