题目:
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?
思路:
与
http://blog.csdn.net/lanxu_yy/article/details/17309079类似,利用快慢指针来判断是否存在环。然后计算环中元素的个数,再利用快慢指针找到环的入口。
代码:
/**
* 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) {
ListNode* slow = head;
ListNode* fast = head;
int retry = 100000;
while(fast!= NULL && fast-> next != NULL && fast->next->next != NULL && retry– > 0){
slow = slow->next;
fast = fast->next;
fast = fast->next;
if(fast == slow){
ListNode* p = fast->next;
int nodeCount = 1;
while(p != fast){
nodeCount++;
p = p->next;
}
slow = head;
fast = head;
while(nodeCount– > 0){
fast = fast->next;
}
while(fast != slow){
slow = slow->next;
fast = fast->next;
}
return fast;
}
}
return NULL;
}
};