142. 环形链表 II
image.png
解法
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
// 快慢指针
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
// 相遇后,相遇点指针和头指针同时走,会走到环入口
// 公式为(x+y)*2 = x + y + (y + z)* n
// 当n为1时,x=z,不为1时,相遇点指针多转几圈
while (fast != head) {
fast = fast.next;
head = head.next;
}
return head;
}
}
return null;
}
}
本文标题:142. 环形链表 II
本文链接:https://www.haomeiwen.com/subject/hmcpiltx.html
网友评论