------QUESTION------
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?
思路:设head距离循环开始点k,循环开始点距离fast和slow第一次相遇点x,slow还要走y到达循环开始点。则有:x+y+k=n;
n+x= 2* (k+n);得到y=k。及相遇点到循环开始点的距离与head到循环开始点的距离相等,那么把slow放到head,fast和slow都用pace=1行走,则在循环开始点两者将相遇。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
bool flag = false;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast) {
slow = head;
flag = true;
break;
}
}
if(!flag) return NULL;
while(fast!=slow){
fast = fast->next;
slow = slow->next;
}
return fast;
}
};