/*
 public class ListNode {
    int val;
    ListNode next = null;

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

    public ListNode EntryNodeOfLoop(ListNode pHead) {
        if(pHead == null || pHead.next == null) {
            return null;
        }
        ListNode s = pHead, f = pHead.next;
        while(true) {
            if(f.next == null) {
                return null;
            }
            f = f.next;
            if(f == s) {
                break;
            }
            if(f.next == null) {
                return null;
            }
            f = f.next;
            if(f == s) {
                break;
            }
            s = s.next;
        }
        Set<ListNode> ring = new HashSet<>();
        ring.add(s);
        s = s.next;
        while(s != f) {
            ring.add(s);
            s = s.next;
        }
        while(true) {
            if(ring.contains(pHead)) {
                return pHead;
            }
            pHead = pHead.next;
        }
    }
}