- Linked List Cycle II My Submissions QuestionEditorial Solution
Total Accepted: 74093 Total Submissions: 235430 Difficulty: Medium
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?
思路:假设快慢指针在x处相遇,
此时快指针在环内假设走了n圈加x步,而总的步数:nr+x+a
是慢指针的2倍
即有nr+x+a =(x+a)*2
上式为a=(n-1)r+r-x;
说明慢指针走到a时候,快指针从x处走了r-x前一个加上n-1圈的距离,
注意此时快指针从X处一步一步走,慢指针也一步一步走,直到在入口相遇
时间复杂度:O(n)
空间复杂度:O(1)
/**
* 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||head->next==NULL)return NULL;
ListNode *p_quick=head,*p_slow=head;
while(p_quick!=NULL&&p_quick->next!=NULL){
p_quick = p_quick->next->next;
p_slow = p_slow->next;
if(p_quick==p_slow)break;
}
if(p_quick==p_slow){
p_slow=head;
while(p_slow!=p_quick){
p_slow = p_slow->next;
p_quick=p_quick->next;
}
return p_slow;
}
else return NULL;
}
};