zoukankan      html  css  js  c++  java
  • linked-list-cycle-ii 链表中的环

    题目:

    对于一个给定的链表,返回环的入口节点,如果没有环,返回null
    拓展:
    你能给出不利用额外空间的解法么?

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

    代码:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *detectCycle(ListNode *head) {
    12         if(head == NULL)
    13             return NULL;
    14         ListNode* slow = head;
    15         ListNode* fast = head;
    16         while(fast != NULL && fast->next != NULL){
    17             fast = fast->next->next;
    18             slow = slow->next;
    19             if(slow == fast)
    20                 break;
    21         }
    22         if(fast == NULL || fast->next == NULL)
    23             return NULL;
    24         fast = head;
    25         while(fast != slow){
    26             fast = fast->next;
    27             slow = slow->next;
    28         }
    29         return slow;
    30     }
    31 };

    我的笔记:

    1)同linked-list-cycle-i一题,使用快慢指针方法,判定是否存在环,并记录两指针相遇位置(Z);
    2)将两指针分别放在链表头(X)和相遇位置(Z),并改为相同速度推进,则两指针在环开始位置相遇(Y)。

    证明如下:
    如下图所示,X,Y,Z分别为链表起始位置,环开始位置和两指针相遇位置,则根据快指针速度为慢指针速度的两倍,可以得出:
    2*(a + b) = a + b + n * (b + c);即
    a=(n - 1) * b + n * c = (n - 1)(b + c) +c;
    注意到b+c恰好为环的长度,故可以推出,如将此时两指针分别放在起始位置和相遇位置,并以相同速度前进,当一个指针走完距离a时,另一个指针恰好走出 绕环n-1圈加上c的距离。
    故两指针会在环开始位置相遇。
    注意:快慢指针第一次相遇的时候一定是在第一圈内,因为快指针对慢指针来说,每次两者之间的距离都在 -1,而当慢指针刚进入环时,与快指针的距离 <= b + c,而慢指针距离环的距离也一定 <= b + c,因此,快指针一定能在慢指针进入环后第一圈追上。
     
  • 相关阅读:
    bootstrap如何设置每一个选项卡对应一个页面
    SpringBoot集成百度UEditor图片上传后直接访问404解决办法
    从0开始完成SpringBoot+Mybatis实现增删改查
    Luarocks 安装艰难过程
    [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1076)')))
    python + selenium 搭建环境步骤
    mongodb的安装
    git-新建git用户流程-1
    git-关联远程git仓库详细步骤-2
    Django启动服务的流程
  • 原文地址:https://www.cnblogs.com/john1015/p/13255817.html
Copyright © 2011-2022 走看看