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

判断链表中是否有环

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

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

/**
 * 
 * @param head ListNode类 
 * @return bool布尔型
 */
bool hasCycle(struct ListNode* head ) {
    // write code here
    struct ListNode* low = head;
    struct ListNode* fast = head;
    int q=0;
    while(fast != NULL && fast->next != NULL){
        
        if(low->next == fast->next->next){
            struct ListNode* head1 = head;
            struct ListNode* head2 =low->next;
            while(head1 != head2){
                head1 = head1->next;
                head2 = head2->next;
                q++;//计算环的入口
            }
            return true;
        }
        low = low->next;
        fast = fast->next->next;

    }
    return false;
}

全部评论

相关推荐

专心打鱼:互联网搬运工,贴子都要偷
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务