题目
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?
分析
一个指针进入环,计算环内节点数量,另一指针从头开始移动,慢指针移动一个位置,快指针转一圈,快慢指针相同时,为环的开始。
复杂度
复杂度与环的大小有关。最大O(n)。
无环:O(n)
有环:O(n)~O(n^2)
CODE
/**
* 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 *slow = head;
ListNode *fast = slow->next;
while (fast) {
fast = fast->next;
if (fast) {
fast = fast->next;
}
slow = slow->next;
if (fast == slow) {
break;
}
}
if (!fast) {
return NULL;
}
// there is a cycle
int count = 1;
fast = slow->next;
while (slow != fast) {
fast = fast->next;
++count;
}
slow = head;
while (1) {
for (int i = 0; i < count; ++i) {
if (slow == fast) {
return slow;
}
fast = fast->next;
}
slow = slow->next;
}
}
};
龟兔赛跑
It is a famous known problem Hare and Tortoise Length of head to cycle started node:x
Length of the cycle: y
Let hare run two steps while tortoise runs one step
while both of them entered the cycle, the hare is definetly to overlap the tortoise at some node, we define it as m:
The hare totally runs: x + ky + m The tortoise totally runs: x + ty + m Thus, ky = 2ty + x + m we have (x + m) mod y = 0 We can conclude that if the hare run more x steps, it will reach the cycle's starting node.
x+ky+m = 2*(x+ty+m) => ky = 2ty+x+m => x+m = (k-2t)y => (x+m)%y == 0
stackpop的代码
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ListNode* slow = head;
ListNode* fast = head;
do{
if( !slow || !fast ) return NULL;
slow = slow->next;
fast = fast->next;
if( fast ) fast = fast->next;
else return NULL;
}while( slow != fast );
slow = head;
while( slow != fast ){
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
我的
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (!head) {
return NULL;
}
ListNode *slow = head;
ListNode *fast = head;
while (fast) {
slow = slow->next;
fast = fast->next;
if (fast) {
fast = fast->next;
}
if (slow == fast) {
break;
}
}
if (!fast) {
return NULL;
}
slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
};