题解 | #链表中环的入口结点#
链表中环的入口结点
http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
ArrayList<Integer> arr = new ArrayList<>();//定义存放值的list
if(pHead==null){
return null;
}
boolean is = isLoop(pHead);//判断是不是环形
ListNode head = pHead;
if(is){
while(true){
if(arr.contains(head.val)){//如果遇到第一个值相同了那么这个点就是顶点。
return head;
}else{
arr.add(head.val);
head = head.next;
}
}
}
return null;
}
//判断是否能构成环(定义两个指针一次跳一下,一次跳两下,如果有环那么这两个指针一定会相遇)
//(类比操场跑步。一个人跑的块,一个人跑的慢,如果操场是环形,那么跑的快的和跑的慢的一定会重合。)
public boolean isLoop(ListNode head){
ListNode point1 = head;
ListNode point2 = head;
while(true){
try{
point1 = point1.next;
point2 = point2.next.next;
if(point1==point2){
return true;
}//这里用异常判断算是一种新思路吧,如果不是环形那么会报错的。
}catch(Exception e){
return false;
}
}
}}

