mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-05 03:36:39 +08:00
添加141.LinkedListCycle的Java解法
This commit is contained in:
@ -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;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user