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?
这道题让我很无语,感觉我的算法和AC的应该是一样的,但是就是TLE,贴出来:
/**
* 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) {
// 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;
}
};
上面是AC的,下面是自己写的TLE:
/**
* 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)
{
return NULL;
}
ListNode *pSingleSpeed=head;
ListNode *pDpubleSpeed=head;
while (pSingleSpeed!=NULL&&pDpubleSpeed!=NULL)
{
pSingleSpeed=pSingleSpeed->next;
pDpubleSpeed=pDpubleSpeed->next;
if (pDpubleSpeed!=NULL)
{
pDpubleSpeed=pDpubleSpeed->next;
}
/* else
{
return NULL;
}*/
if (pSingleSpeed==pDpubleSpeed/*&&pSingleSpeed!=NULL
&&pDpubleSpeed!=NULL*/)
{
break;
}
}
if (pDpubleSpeed==NULL||pSingleSpeed==NULL)
{
return NULL;
}
pDpubleSpeed=head;
while (pDpubleSpeed!=pSingleSpeed)
{
pSingleSpeed=pDpubleSpeed->next;
pSingleSpeed=pSingleSpeed->next;
}
return pSingleSpeed;
}
};
两者思想都是一样的,先判断是否具有回路,如果有,让一个指针回到起点,两个指针以相同速度继续走,在此相遇地点就是环的入口,如果不清楚,画图一看就知道了。