题目描述
一个链表中包含环,请找出该链表的环的入口结点
思路:利用hashset不可以存重复元素的特点,add方法返回类型为boolean。那么ListNode不是基本类型,可以比较吗?ListNode虽然不是基本类型,但是比较时比较的是对象地址,是可以比较的。
public class EntryNodeOfLoop {
public ListNode method(ListNode pHead){
HashSet<ListNode> set=new HashSet<ListNode>();
while(pHead!=null){
if(!set.add(pHead))
return pHead;
pHead=pHead.next;
}
return null;
}
}