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?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == NULL)
return NULL;
ListNode* fast = head->next;
ListNode* slow = head;
while (fast != NULL) {
if (fast == slow) {
break;
}
slow = slow->next;
fast = fast->next;
if (fast != NULL)
fast = fast->next;
}
if (fast != NULL) {
int count = 1;
while (slow->next != fast){
++count; //统计环中结点的个数
slow = slow->next;
}
slow = fast = head;
for (int i = 0; i < count;i++)
fast = fast->next;
while (slow != fast)
{
fast = fast->next;
slow = slow->next;
}
}
return fast;
}
};