题解 | #牛牛队列成环#

牛牛队列成环

https://www.nowcoder.com/practice/38467f349b3a4db595f58d43fe64fcc7

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return bool布尔型
     */
    bool hasCycle(ListNode* head) {
        // 解题思路:就是在圆形跑道上跑步,快的总会和慢的相遇
        if(head == nullptr || head->next == nullptr){
            return false;
        }
        ListNode* fastP = head;
        ListNode* slowP = head;
        while(fastP && fastP->next){
            fastP = fastP->next->next;
            slowP = slowP->next;
            if(fastP != nullptr){ // 这里有可能会产生空,那么访问一个空指针的解应用是非法的
                if(fastP->val == slowP->val){ // 这里是强调的编号唯一
                    return true;
                    break;
                }
            }

        }
        return false; 
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务