其他分享
首页 > 其他分享> > 【链表】lc141.判断链表是否有环

【链表】lc141.判断链表是否有环

作者:互联网

原题链接

思路

参考代码(Java)

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;
}
public ListNode detectCycle(ListNode head) {
    ListNode fast = head;
    ListNode slow = head;
    while(fast!=null && fast.next!=null){
        fast = fast.next.next;
        slow = slow.next;
        if(fast == slow){
        	// 可以确定有环,然后将快指针指向头结点,等他们再次相交时,交点就是环的入口
            fast = head;
            while(fast!=slow){
                fast = fast.next;
                slow = slow.next;
            }
            return fast;
        }
    }
    return null;
}

标签:head,slow,ListNode,fast,next,链表,有环,null,lc141
来源: https://blog.csdn.net/Awt_FuDongLai/article/details/120969608