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?
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
bool flag = false;
ListNode *fast, *slow;
fast = slow = head;
while(fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
if(fast == slow) {
flag = true;
break;
}
}
if(!flag) return NULL;
int count = 1; // count表示环的长度
fast = fast->next->next;
slow = slow->next;
//当fast与slow重合后,还需count-1次才能重新重合
while(fast != slow) {
fast = fast->next->next;
slow = slow->next;
count++;
}
fast = slow = head;
while(count--) fast = fast->next;
while(fast != slow) {
fast = fast->next;
slow = slow->next;
}
return fast;
}
};