leetcode 142. 环形链表 II


一、题目

输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。

二、解法

快慢指针。

slow跑了a+b,fast跑了a+b+n(b+c)(n大于等于1的正整数),则有 2(a+b)=a+b+n(b+c),化简得a=(n-1)(b+c)+c,可见,如果相遇后把slow重新放回head,和fast每次进一步,slow和fast将在环起点处相遇。

/**
 * 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) {
        ListNode slow=head,fast=head;
        do{
            if(fast==null||fast.next==null) return null;
            fast=fast.next.next;
            slow=slow.next;
        }while(slow!=fast);
        slow=head;
        while(slow!=fast){
            slow=slow.next;
            fast=fast.next;
        }
        return fast;
    }
}

相关