题目描述

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中,要求使用O(1)的空间复杂度

链接:https://leetcode-cn.com/problems/linked-list-cycle-ii

解题思路

111 环形链表 II - 图1
a+(n+1)b+nc=2(a+b)⟹a=c+(n−1)(b+c)
即有a = (n-1)(b+c) + 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. ListNode* fast=head;
  13. ListNode* slow=head;
  14. while (slow != NULL && fast != NULL) {
  15. slow = slow->next;
  16. if (fast->next == NULL)
  17. return NULL;
  18. fast = fast->next->next;
  19. if (slow == fast)
  20. break;
  21. }
  22. if (slow==NULL || fast==NULL)
  23. return NULL;
  24. ListNode* pivot=head;
  25. while (pivot != slow) {
  26. pivot = pivot->next;
  27. slow = slow->next;
  28. }
  29. return pivot;
  30. }
  31. };