leetcode笔记:Linked List Cycle 2

一. 题目描述

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up: Can you solve it without using extra space?

二. 题目分析

在Linked List Cycle题目中,使用了两个指针fast与slow检查链表是否有环,该题在此基础上,要求给出链表中环的入口位置,同样需要注意空间复杂度。为了方便解释,以下给出一个有环链表:

这里写图片描述

其中,设链表头节点到环入口处的距离为X,环长度为Y,使用fastslow两个指针,fast指针一次前进两步,slow指针一次前进一步,则他们最终会在环中的K节点处相遇,设此时fast指针已经在环中走过了m圈,slow指针在环中走过n圈,则有:

fast所走的路程:2*t = X+m*Y+K

slow所走的路程:t = X+n*Y+K

由这两个方程可得到:

2X + 2n*Y + 2K = X + m*Y + K

进一步得到: X+K = (m-2n)Y

X+K = (m-2n)Y 可发现,X的长度加上K的长度等于环长度Y的整数倍!因此可得到一个结论,即当fastslow相遇时,可使用第三个指针ListNode* cycleStart = head;,从链表头节点往前走,slow指针也继续往前走,直到slowcycleStart相遇,该位置就是链表中环的入口处。

三. 示例代码

#include <iostream>
using namespace std;

struct ListNode
{
    int value;
    ListNode* next;
    ListNode(int x) :value(x), next(NULL){}
};

class Solution
{
public:
    ListNode *detectCycle(ListNode *head)
    {
        if (head == NULL || head->next == NULL || head->next->next == NULL)
            return head;
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast->next->next)
        {
            fast = fast->next->next;
            slow = slow->next;
            if (fast == slow)
            {
                ListNode* cycleStart = head;
                while (slow != cycleStart)
                {
                    slow = slow->next;
                    cycleStart = cycleStart->next;
                }
                return cycleStart;
            }
        }
        return NULL;
    }
};

一个有环链表,环从第二个节点开始:

这里写图片描述

四. 小结

解答与链表有关的题目时,要多画图,找规律,否则容易遇到各种边界问题。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值