描述:
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
示例 :
输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。
![](https://img-blog.csdnimg.cn/img_convert/989d88625af9528408c1f834de4e7bfc.png)
图片分析:
![](https://img-blog.csdnimg.cn/img_convert/2ac6c39d4548fa9c59e8eb1b7c68f9f8.png)
代码分析:
public class Solution {
public ListNode detectCycle(ListNode head) {
//如果链表为空直接返回null
if(head == null)return null;
ListNode slow = head,fast = head,cur = head;
while(fast!=null)
{
slow = slow.next;
if(fast.next!=null)
{
fast = fast.next.next;
}
else
{
return null;
}
if(fast == slow)
{
while(cur!=slow)
{
cur = cur.next;
slow = slow.next;
}
return cur;
}
}
return null;
}
}