141. Linked List Cycle

来源:互联网 发布:xbox软件是什么 编辑:程序博客网 时间:2024/06/06 03:59

Given a linked list, determine if it has a cycle in it.


class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(!head) return false;
        ListNode* slow=head;
        ListNode* fast=head->next;
        while(fast!=slow&&fast&&fast->next)
        {
            slow=slow->next;
            fast=fast->next->next;
        }
        if(fast==slow)
            return true;
        else
            return false;
    }
};
呵呵哒!又是1.88!老子太失落!
学习大佬的代码:
bool hasCycle(ListNode *head) 
{
    ListNode *fast;
    fast = head;
    while (head)
    {
        head = head->next;
        if (fast->next && fast->next->next)
            fast = fast->next->next;
        else
            return false;
            
        if (fast == head)
            return true;
    }
    
    return false;
}
这个速度快一点,不过没啥大区别

原创粉丝点击