Leetcode142. Linked List Cycle II

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head==null) return null;
        
        //判断是否有环
        ListNode fast = head.next, slow = head;
        while(fast!=slow){
            if(fast==null||fast.next==null||fast.next.next==null) return null;
            fast = fast.next.next;
            slow = slow.next;
        }
        
        //出循环说明有链
        //找出链的长度n
        fast = fast.next;
        int n = 1;
        while(fast!=slow){
            fast = fast.next;
            n++;
        }
        
        //fast从头先走n步
        fast = head;
        for(int i=0;i<n;i++) fast = fast.next;
        
        //slow从头走,fast继续,走到相遇,走了s步,则相遇位置应该为入口 s+n=总长度
        slow = head;
        while(slow!=fast){
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle II.
Memory Usage: 35.2 MB, less than 5.33% of Java online submissions for Linked List Cycle II.

posted @ 2019-03-29 11:15  大胖子球花  阅读(110)  评论(0)    收藏  举报