问题描述
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?解决思路
参考141题。我们假定第一次两个指针相遇的指针与开始指针的距离为s,回路的长度为r,回路开始的指针和开始指针的距离为k,两个指针相遇的指针与回路开始指针的距离为m。
有 2s - s = nr,k = s - m = nr - m = (n-1)r + (r-m)
所以我们需要求k,只需要在第一次相遇后,将其中一个节点放到开始节点,一个不动,重新开始以1步的距离走路,下一次相遇的节点,就是回路开始的节点。(因为再走k次,回路中的节点可以往前r-m个位置,即回到了回路开始的节点。)代码
/**
* 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)
return NULL;
ListNode *walk = head, *run = head;
bool flag = false;
while(walk->next != NULL && run->next != NULL && run->next->next != NULL) {
walk = walk->next;
run = run->next->next;
if (walk == run){
flag = true;
break;
}
}
if (!flag)
return NULL;
walk = head;
while(walk != run) {
walk = walk->next;
run = run->next;
}
return walk;
}
};