Linked List Cycle II

来源:互联网 发布:朱元璋 厉害知乎 婚姻 编辑:程序博客网 时间:2024/06/08 17:01

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

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

class Solution {public:ListNode *detectCycle(ListNode *head){if (!head || !head->next)return NULL;ListNode *slow=head, *fast=head;while (fast && fast->next){fast = fast->next->next;slow = slow->next;if (fast == slow)break;}fast = head;while (slow){if (slow == fast)return slow;fast = fast->next;slow = slow->next;}return NULL;}};
定理:碰撞点p到连接点的距离=头指针到连接点的距离!可参考前一篇博文~

0 0