zoukankan      html  css  js  c++  java
  • LeetCode

    如果一个链表有环,求环的起始位置。

    设置一个快指针每次走两步,一个慢指针每次走一步。若最终能相遇,则有环。如图:

    设:链表头是X,环的第一个节点是Y,slow和fast第一次的交点是Z。各段的长度分别是a,b,c,如图所示。环的长度是L。

    第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。

    因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c。

     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 || head->next == NULL)
    13             return NULL;
    14             
    15         ListNode *slow = head->next;
    16         ListNode *fast = head->next->next;
    17         
    18         while (fast && fast != slow)
    19         {
    20             slow = slow->next;
    21             fast = fast->next ? fast->next->next : fast->next;
    22         }
    23         
    24         if (fast == NULL)
    25             return NULL;
    26             
    27         for (fast = head; fast != slow; fast = fast->next)
    28             slow = slow->next;
    29         
    30         return slow;
    31     }
    32 };
  • 相关阅读:
    centos7.5部署mysql cluster NDB总结
    读《构建之法》13--17章有感
    读《构建之法》8--10章
    作业5.2
    作业5.1
    读《构建之法》6--7章读后感
    做汉堡,做汉堡
    《构建之法》1—5章读后感
    第二次作业
    1
  • 原文地址:https://www.cnblogs.com/bournet/p/4392401.html
Copyright © 2011-2022 走看看