LC142. 环形链表 II

 力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head;   
        ListNode slow = head;

        while(true){
            if(fast == null || fast.next == null)
                return null;
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) break;
        }

        fast = head;

        while(slow != fast){
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }
}

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