LeetCode OJ入门初探-141. Linked List Cycle

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;
}
};

 

整理思路之后想到了差速法:

        ListNode *slow = head;

        ListNode *fast = head;

        

        do

        {

            if(!slow || !fast)

                return false;

            slow = slow->next;

            fast = fast->next;

            if(fast)

                fast = fast->next;

            else

                return false;

        } while(slow != fast);

       return true;     

       }

 

发表评论