题目描述:给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
链接:https://leetcode-cn.com/problems/linked-list-cycle-ii
示例1:
输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。
示例2:
输入:head = [1,2], pos = 0
输出:返回索引为 0 的链表节点
解释:链表中有一个环,其尾部连接到第一个节点。
示例3:
输入:head = [1], pos = -1
输出:返回 null
解释:链表中没有环。
求解思路:快慢指针交点到环入口点的距离等于链表头到环入口点的距离。
- 创建快慢指针,循环寻找快慢指针的交点,找到交点后break循环;
- 若链表指向存在null(即循环结束),则链表为无环链表,返回null;
- 让cur从链表头部head开始走,让fast或slow(此处fast和slow是相同位置)从交点处走,cur与fast或slow的交点即为环的入口点。(交点到环入口点距离等于头到入口点距离)。
代码实现:
public class Solution {
public ListNode detectCycle(ListNode head) {
//1.处理特殊情况
if(head == null){
return null;
}
//2.快慢指针,寻找快慢指针的交点
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
break;
}
}
//3.链表指向存在null,则链表为无环链表
if(fast == null || fast.next == null){
return null;
}
//4.让cur从链表头部head开始走,让fast或slow从交点处走,cur与fast的交点即为环的入口点。(交点到环入口点距离等于头到入口点距离)
ListNode cur = head;
while(cur != fast){
cur = cur.next;
fast = fast.next;
}
return cur;
}
}