• 142.环形链表Ⅱ :::info 找到是否有环,返回入口 ::: 代码:(详细注释)
      1. class Solution {
      2. public:
      3. ListNode *detectCycle(ListNode *head) {
      4. ListNode* fast = head;
      5. ListNode* slow = head;
      6. while(fast != NULL && fast->next != NULL) {
      7. slow = slow->next;
      8. fast = fast->next->next;
      9. // 快慢指针相遇,此时从head 和 相遇点,同时查找直至相遇
      10. if (slow == fast) {
      11. ListNode* index1 = fast;
      12. ListNode* index2 = head;
      13. while (index1 != index2) {
      14. index1 = index1->next;
      15. index2 = index2->next;
      16. }
      17. return index2; // 返回环的入口
      18. }
      19. }
      20. return NULL;
      21. }
      22. };
      分析:
      经典题目

    重要内容:
    image.png
    slow一定是在第一次入环就遇到了fast,而fast则可能已经在环里饶了好几圈了,。
    不管饶了多少圈,反正,从头结点出发一个指针,从相遇节点 也出发一个指针,这两个指针每次只走一个节点, 那么当这两个指针相遇的时候就是 环形入口的节点

    此外,这是因为fast是走两步,slow是走一步,其实相对于slow来说,fast是一个节点一个节点的靠近slow的,所以fast一定可以和slow重合。