题解 | #判断链表中是否有环#

判断链表中是否有环

https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

#include <stdbool.h>
/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

/**
 * 
 * @param head ListNode类 
 * @return bool布尔型
 */
typedef struct ListNode ListNode;

bool hasCycle(struct ListNode* head ) {
    if(head==NULL||head->next==NULL){
        return false;
    }
    // write code here
    //快慢指针
    //快指针走两步,慢指针走1步,如果快指针等于慢指针则就是为环
    ListNode* slow=head;
    ListNode* fast=head->next;
    while(slow!=fast){
        if(fast==NULL||fast->next==NULL){
            return false;
        }
        slow=slow->next;
        fast=fast->next->next;
    }
    return true;
}

全部评论

相关推荐

脾气小祖宗:这简历摸到都得狠狠地消毒液洗手😂
点赞 评论 收藏
分享
10-10 11:38
已编辑
湖南理工大学 Java
小浪_Coding:多沟通叭, 公式简历+学历一般的话难找
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务