题目链接:https://leetcode.cn/problems/linked-list-cycle/
思路:判断链表是否有环经典解法-快慢指针。初始化指针fast和slow均指向链表头结点head,接下来fast每次前进两步,slow每次前进一步。然后接两句话:无环链表必有头,有环链表追得上。代码如下:
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null) return false;
ListNode fast = head;
ListNode slow = head;
//无环链表有终点,有环链表追得上
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if(slow == fast) {
return true;
}
}
return false;
}
}