题目
这道题是141.环形链表的增强版 我们不仅需要判断是一个环形链表 还需要找到入环点
思路
画图证明
我们可以证明出
代码描述
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null){//空链表返回空
return null;
}
ListNode slow = head;
ListNode fast = head;
//定义快慢指针
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
break;
}
}
//找到第一次相遇的点
if(fast == null || fast.next == null){
return null;
}
//循环结束条件可能是无环 这个语句判断是不是因为无环而退出的循环
//如果是则返回null
fast = head;
//将快指针指向头节点 开始查找入环点
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
//找到入环点
return fast;
}
}