题目描述:
链接https://leetcode-cn.com/problems/linked-list-cycle/
代码:
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null){
return false;
}
//快慢指针法
ListNode slow = head;
ListNode fast = head.next;
//无环 跳出循环
while(fast.next != null && fast.next.next != null){
//有环 就会相遇
if(slow == fast){
return true;
}
//慢指针走一步
//快指针走两步
slow = slow.next;
fast = fast.next.next;
}
return false;
}
}