题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路
1、判断有无环:快慢指针,快指针一次走两步,慢指针一次走一步,两个指针若指向相同–有环,否则,无环【类比两个人跑步,有环的快的一定能和慢的相遇】
2、找入口结点:入口节点到相遇点的距离=头节点到入口结点的距离
代码
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
if(pHead == null || pHead.next == null) return null;//先判断一下
ListNode fast = pHead;
ListNode slow = pHead;
boolean isLoop = false;
while(fast != null){//判断是否有环
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
isLoop = true;
break;//注意一定要有break
}
}
if(isLoop){
slow = pHead;
while(slow != fast){//找到入口结点
slow = slow.next;
fast = fast.next;
}
return slow;
}
return null;
}
}