Skip to content

142. linked list cycle II

难度:Medium

刷题内容

原题连接

  • https://leetcode.com/problems/linked-list-cycle-ii/

内容描述

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

解题方案

思路 **- 时间复杂度: O(N)*- 空间复杂度: O(1)***

上一道题已经解决了链表是否有环的问题,那么如何判断环的入口在哪里,我们先设入口链表的头的距离为m,两个人指针相遇的节点距离入口为x,l2比l1多走 n 圈,环部分的链表长度为p。这样,我们就得到了如下公式。

2(m + x) = m + n * p + x

化简得到

m = n * p - x

接着我们再定义一个指针 ret,当 ret 移动 m 个,l1刚好移动 n * p - x,就是二者相遇的地方即为入口

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode * head) {
        if(head == nullptr)
        return nullptr;
    ListNode* l1 = head,*l2 = head;
    int count1 = 0,count2 = 0;
    while(1)
    {
        if(l2 == nullptr || l2 ->next == nullptr)
            return nullptr;
        l1 = l1 ->next;
        ++count1;
        l2 = l2 ->next ->next;

        ++count2;
        if(l1 == l2)
            break;
    }
    ListNode* ret = head;
    while(1)
    {
        if(l1 == ret)
            return ret;
        ret = ret ->next;
        l1 = l1 ->next;
    }
    }
};

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组