题目描述:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
读题:
找出链表中是否有环,若有,返回环开始的结点。
解题思路:
要检测链表是否有环,使用快慢指针,慢指针一次走一个结点,快指针一次走两个结点,若有环,在遍历这个环一次或多次后,两个指针会相遇。
难点在于怎么知道环的开始结点是哪个。
将链表有环的形态用图形模拟一下。
head是链表的head,start是环的开始结点,meet是快慢指针相遇的结点。
S:从head到start的距离;
L1:start到meet的距离(绿色线条)
L2:meet回到start的距离(棕色线条)
因为慢指针一次走一个结点,快指针一次走两个结点,所以当他们相遇时,慢指针走过了S+L1,快指针走过了S+L1+L2+L1
可得
2*(S+L1)=S+L1+L2+L1 即
S=L2
若S很长的情况下,快指针可能在环内走了几遍才与慢指针相遇,这时
S=L2+nL(n=0,1,2,…;L为整个环的长度,即L1+L2)
S的终点是start结点,L2的终点也是start结点
也就是说,从head到start与从meet到start的距离是一样的。
一个指针从head开始,一个指针从meet开始,一起往下走,当他们相遇,即为start结点。
提交代码:
/**
* 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 *slow = head, *fast = head;
ListNode *st = NULL;
while(fast && fast->next) {
slow = slow->next;
fast= fast->next->next;
if (slow == fast) {
fast = head;
while (fast!=slow) {
slow = slow->next;
fast = fast->next;
}
st = slow;
break;
}
}
return st;
}
};