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

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

    public ListNode EntryNodeOfLoop(ListNode pHead) {
        Set<ListNode> dic = new HashSet<ListNode>();
        while(pHead != null){
            if(dic.contains(pHead)){
                return pHead;
            } else {
                dic.add(pHead);
            }
            pHead = pHead.next;
        }
        return null;
    }
}

利用HashSet的非重复性

  • 将遍历过的节点放入set中,如果后续节点在set中存在,则返回第一个存在的节点
  • 如果没有,则返回null