Linked List Cycle II
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?
与上一题类似,这里我直接复用并修改了上一题的代码。
我们这样来想:
设置两个指针fast和slow,fast指针每次走2步,slow指针每次走1步。
假设进入环之前的路径长为n,环的长度为m。那么当slow指针进入环的第一个节点时,slow指针走了n步,fast指针在环里走了n步。两个指针的距离为m-n步。slow指针每走1步,fast指针都会追近1步。那么,当slow指针走了m-n步时,两个指针相遇。此时,fast-slow指针距离下次抵达环入口的距离为n步。
在fast-slow指针相遇时,在链表入口处放置一个指针p,p指针每次走一步。slow指针也每次走一步。这样当slow和p都再走n步时,两者在环的入口处相遇。即返回结果。
/**
* 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 * p = hasCycle(head);
if(p == NULL){//no circle
return NULL;
}
ListNode * q = head;
while(q != p){
p = p->next;
q = q->next;
}
return p;
}
ListNode * hasCycle(ListNode *head) {
ListNode * fast, * slow;
if(head == NULL){
return NULL;
}
fast = slow = head;
while(true){
if(fast->next == NULL || fast->next->next == NULL){
return NULL;//no circle
}
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
return fast;
}
}
}
};
