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.

Follow up:
Can you solve it without using extra space?

 

头结点到cycle begins的点 距离是A, cycle begins的点 到快慢结点相遇的 点的距离是B

A+B+N = 2*(A+B)

A+B = N

所以 快慢指针相遇后,从头结点开始再跑一个慢指针,直到2个慢的相遇,相遇的点就是cycle begin

 

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* slow = head;
        ListNode* fast = head;
        while(slow != NULL &&  fast != NULL && fast->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast) break;
        }
        // fast 遇到空指针说明没有环
        if(fast == NULL || fast->next == NULL) return NULL;
        // slow 从头跑一遍
        slow = head;
        while(slow!=fast) {
            slow = slow->next;
            fast = fast->next;
        }
        return slow;
    }
};

 

相关文章:

  • 2021-07-27
  • 2021-08-29
  • 2021-12-18
猜你喜欢
  • 2022-01-05
  • 2021-05-03
  • 2022-12-23
  • 2021-11-20
  • 2022-12-23
  • 2021-06-24
  • 2021-12-10
相关资源
相似解决方案