首页 > 其他分享 >【链表】LeetCode 141. 环形链表

【链表】LeetCode 141. 环形链表

时间:2023-01-03 10:11:09浏览次数:46  
标签:head slow 141 fast 链表 null LeetCode

题目链接

141. 环形链表

思路

设置fast指针和slow指针,分别走两步和一步,如果链表有环的话,那么两个指针一定会在某一时刻相遇。

可以想象成速度不同的两个人跑圈,只要时间足够,速度慢的人一定会被速度快的人套圈。

代码

class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null){
            return false;
        }

        ListNode slow = head;
        ListNode fast = head;

        do{
            slow = slow.next;
            fast = fast.next;
            if(fast != null){
                fast = fast.next;
            }
        }while(slow != null && fast != null && slow != fast);

        return fast != null;
    }
}

标签:head,slow,141,fast,链表,null,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17021205.html

相关文章