链表经典面试题(六)

判断链表是否有环

    • 1.题目
    • 2.思路分析(文字)
    • 3.详细的注释和代码实现

1.题目

链表经典面试题(六)_第1张图片

2.思路分析(文字)

在这里插入图片描述

3.详细的注释和代码实现

public class Solution {
    public boolean hasCycle(ListNode head) {
        //定义两个快慢指针
        ListNode fast = head;
        ListNode slow = head;
        //让快指针走两步,慢指针走一步
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                return true;
            }
        }
        return false;
    }
}

你可能感兴趣的:(链表,数据结构)