/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null || head.next == null){
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        
        while(slow != fast){
            if(fast == null || fast.next == null){
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }
}

快慢指针

  • 如果存在环的话,快慢指针从开始同时出发,则一定会再次相遇
  • 如果不存在环,则快指针就会停在null或者快指针的下一步就是null
  • 所以设置slow 每次移动1, fast 每次移动2
  • 但是这种就会出现一个问题,因为循环的结束条件是 slow == fast,所以如果初始化都是head的话,不能进入循环,所以让fast 为 head.next ,这样就相当于有一个哑节点在head前面,达成的效果是一样的