LeetCode 141. 环形链表

/**
 * 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){
            return false;
        }
        //定义快慢指针
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null){
            //慢指针一次走一步,快指针走俩布
            slow = slow.next;
            fast = fast.next.next;
            //如果相遇,则有环
            if(fast == slow){
                return true;
            }
        }
        return false;
    }
}
原文地址:https://www.cnblogs.com/peanut-zh/p/13910896.html