使用HashSet类来解决
由于HashSet 是基于 HashMap 来实现的,是一个不允许有重复元素的集合。
因为将链表中所有的结点都遍历一遍,如果有环,那么在使用HashSet.contains()方法时,结果会出现true。
表示这个结点在集合中已经存过了,既这个结点就是 环 的入口结点。
import java.util.HashSet;
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
HashSet<ListNode> set = new HashSet<>();
ListNode temp = pHead;
while(temp != null){
if(set.contains(temp)){
return temp;
}
set.add(temp);
temp = temp.next;
}
return null;
}
}

京公网安备 11010502036488号