Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
一开始写了个算法,结果爆了超时。。。唉
超时算法:每次都计算与头节点的距离。若比上次距离短,则有环:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
int lastdistance = 0;
int nowdistance = 0;
ListNode* temp = head;
while(temp != NULL)
{
temp = temp -> next;
nowdistance = distance(head,temp);
if(nowdistance < lastdistance)
{
return true;
}
else
{
lastdistance = nowdistance;
}
}
return false;
}
int distance(ListNode *head,ListNode *end)
{
int i = 0;
ListNode* temp = head;
while(temp != NULL && temp != end)
{
temp = temp -> next;
i ++;
}
return i;
}
};
整理思路之后想到了差速法: