题目内容:
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?
解题思路:
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 *one = head->next, *two = one->next;
// check whether there is a cycle in list
while(two != NULL && one != two) {
one = one->next;
two = two->next;
if(two == NULL)
break;
two = two->next;
}
if(two == NULL)
return NULL;
// get the length of cycle - clength
int clength(1);
one = one->next;
while(one != two) {
one = one->next;
++clength;
}
ListNode *p = head;
one = head;
for(int i = 0; i < clength; ++i)
p = p->next;
while(p != one) {
p = p->next;
one = one->next;
}
return p;
}
};
2) 深入分析一下指针在查找环过程中的相遇点:
设链表开始处距离环入口处的距离为k,环的长度为c。
当慢指针到达入口处时,它走了k步,而快指针此时已经在环内,一共走了2k步,设此时它距离环的入口n步。那么还需要c-n步,快指针就会和慢指针相遇(快指针每次都赶上慢指针一步)。相遇时的位置就是c-n(慢指针是从环的入口处出发的)。
再考察k与c、n之间的关系。快指针在圈内从起点开始行走了k步到达了n的位置,那么它们之间的关系满足: k=c∗x+n ,x为自然数。
如果从相遇时的位置开始,让慢指针再走 c∗x+n 步,就会又回到入口处的节点。显然k满足条件。因此我们重新设置一个指针指向起始节点,让起始节点的指针和环中慢节点的指针同时向前走k步,这两个指针必然在环的入口处相遇。
实现代码:
/**
* 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 *one = head->next, *two = one->next;
// check whether there is a cycle in list
while(two != NULL && one != two) {
one = one->next;
two = two->next;
if(two == NULL)
break;
two = two->next;
}
if(two == NULL)
return NULL;
ListNode *p = head;
while(p != one) {
p = p->next;
one = one->next;
}
return p;
}
};