java实现快慢指针判断链表有环
时间: 2024-06-17 18:00:53 浏览: 170
在Java中,使用快慢指针(也称为龟兔赛跑法)是常见的判断链表是否有环的方法。这种方法基于两个指针,一个每次移动一个节点,另一个每次移动两个节点。如果链表中有环,那么快指针最终会追上慢指针;如果没有环,快指针会先到达链表尾部。
下面是基本的实现步骤:
1. 初始化两个指针:`slow`(慢指针)和`fast`(快指针),分别指向链表的头节点。
2. 指针遍历:如果链表不为空,循环执行以下操作:
a. `slow`向前移动一步(`slow.next`)。
b. `fast`向前移动两步(`fast.next.next`)。
3. 判断环的存在:如果`fast`指针在某次迭代中到达了`null`,说明链表没有环,因为快指针走过的距离是慢指针的两倍,如果链表长度为偶数,快指针应该在链表末尾找到慢指针,如果奇数,则会先到尾部再回环,不会追上。如果`fast`始终不为`null`,且与`slow`相遇(它们都指向同一个节点),那么链表中存在环。
下面是伪代码形式的实现:
```java
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
// 如果链表为空或只有一个节点,不存在环
if (head == null || head.next == null) {
return false;
}
// 快慢指针开始遍历
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
// 如果快指针先到末尾,则链表无环
if (fast == null) {
return false;
}
// 如果快慢指针相遇,说明链表有环
if (slow == fast) {
return true;
}
}
return false; // 如果没有提前结束循环,说明链表无环
}
```
阅读全文
相关推荐


















