题目
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
不允许修改 链表。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。
解
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = head;
while (fast != null && slow != fast) {
slow = slow.next;
fast = fast.next;
if (fast != null) {
fast = fast.next;
}
}
if (slow != fast) {
return null;
}
int countCycle = 1;
ListNode p1 = slow.next;
while (p1 != slow) {
countCycle++;
p1 = p1.next;
}
// 让p2和head保持环长度的距离,当进入环后,他们之间的距离正好包住环
ListNode p2 = head;
for (int i = 0; i < countCycle; i++) {
p2 = p2.next;
}
while (p2 != head) {
head = head.next;
p2 = p2.next;
}
return head;
}
}