LeetCode-141 linked list cycle 环形链表

版权声明:转载请注明原址,有错误欢迎指出 https://blog.csdn.net/iwts_24/article/details/83421632

题目链接

LeetCode-141 linked list cycle

题意

据说也是面试经典链表题了,判定是否存在环。以此还可以引申很多链表相关题,可以去搜一下,或者看我的博客:

https://blog.csdn.net/iwts_24/article/details/83421853

题解

        其实是比较简单的,因为判定有环的情况下,一直next向下跑是死循环,但是例如高中经典物理题追及问题,一个人速度快一个人速度慢,那么最终是一定会相遇的。我们也可以设定两个指针,一个每次1速向后遍历,另外一个2速遍历,那么如果无环,最终快指针是会成为NULL,而如果有环,那么快指针一定会在某个过程中与慢指针相遇。

        这个题有一点注意,fast.next.next。快指针最好不要这样写,因为如果fast是链表尾(无环的情况),那么fast.next = null,这样调用fast.next.next会抛出异常。所以应该先判定fast.next是否为null。

Java 代码

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null) return false;
        ListNode show = head;
        ListNode fast = head;
        if(fast.next != null) fast = fast.next.next;
        show = show.next;
        while(show != null && fast != null){
            if(show == fast) return true;
            show = show.next;
            if(fast.next == null) return false;
            fast = fast.next.next;
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/iwts_24/article/details/83421632
今日推荐