import java.util.*;
/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {

    public ListNode EntryNodeOfLoop(ListNode pHead) {
        if (pHead == null) {
            return null;
        }
        ListNode slow = hasCycleReturnNode(pHead);
        if (slow == null) {
            return null;
        }
        // 快指针重新回到起始位置,再和慢指针跑一次,
        // 这一次都是一步一步移动,相遇时即为环的入口位置
        ListNode fast = pHead;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }

        return slow;
    }

    /**
     * 先判断有没有环,返回快慢指针相遇时,慢指针的节点
     */
    public ListNode hasCycleReturnNode(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 slow;
            }
        }
        return null;
    }
}