linked-list-cycle

作者: cherryleechen | 来源:发表于2019-05-10 14:04 被阅读0次

    时间限制:1秒 空间限制:32768K

    题目描述

    Given a linked list, determine if it has a cycle in it.
    Follow up:
    Can you solve it without using extra space?

    我的代码

    /**
     * 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) {
            //快慢指针能相遇说明有环
            if((head==nullptr)||(head->next==nullptr)||
               (head->next->next==nullptr))
                return false;
            ListNode* fast=head->next->next;
            ListNode* slow=head->next;
            while((fast->next)&&(fast->next->next)){
                if(fast==slow)
                    return true;
                fast=fast->next->next;
                slow=slow->next;
            }
            return false;
        }
    };
    

    运行时间:19ms
    占用内存:1224k

    相关文章

      网友评论

        本文标题:linked-list-cycle

        本文链接:https://www.haomeiwen.com/subject/pmdwoqtx.html