142. 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.


题目分析:

1、边界情况:链表为空;只有一个节点,指向本节点

2、必须先知道链表存在不存在环(快慢指针),如果不存在就直接返回Null;如果存在环,也只能直接求出快慢指针相交的那个节点,该节点一定是本题的切入点。

3、对于相交节点有它的一个数学推倒,与环入口节点有关。

4、数学推倒:

   设:L = 链表首节点 到 环入口节点的距离

            C = 环中节点个数

            S =环入口节点第一次相遇的节点距离(链表内的节点个数,与G要区分开)

            G = 第一次相遇的节点距离 到 环入口节点的距离(向链表前进方向,包含环的那一段,G + S = C)

   到第一次相遇时有:           

           慢指针走过的路程S1=L + S

           快指针走过的路程S2 =L + n *C + S(相遇时,快指针绕环走n圈, n >= 1)

           S1 * 2 =S2,可得L = n *C - S = n * C -( C-G ) = (n - 1)*C + G

   因此令指针A指向首节点,B指向相遇节点,两个指针都一步步向后走,会在环入口节点相遇!!!

   指针A走过L步,到入口节点

   指针B走过L =(n - 1)*C + G 步,不管B走了多少圈,最后的G步一定会指向入口节点,因为G的定义就是这个,啊哈哈哈哈!!!

   推倒完毕。(自己写一遍才理解好,我好菜鸡......)


思路:

1、首先处理边界情况

2、判断链表是否存在环,有的话返回相遇节点;没有直接返回Null

3、根据上边的数学推倒,寻找入口


代码:

/**
 * 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 || head->next == nullptr)    return nullptr;
        if (head->next == head)    return head;
        ListNode* node = hasCycle(head);
        if (node == nullptr)    return nullptr;
        if (node == head)   return head;
        ListNode* now = head;
        while (now != node)
        {
            now = now->next;
            node = node->next;
        }
        return now;
    }
    
    ListNode* hasCycle(ListNode* head)
    {
        if (head == nullptr || head->next == nullptr)   return nullptr;
        ListNode* pslow = head;
        ListNode* pfast = head;
        while (pfast->next != nullptr && pfast->next->next != nullptr)
        {
            pfast = pfast->next->next;
            pslow = pslow->next;
            if (pfast == pslow)
                return pslow;
        }
        return nullptr;
    }
};

注:推倒是看了其他帖子后才懂的。共勉!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值