力扣(LeetCode)141.环形链表(Linked List Cycle)

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

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Example 1:
在这里插入图片描述

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Example 2:
在这里插入图片描述

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

Example 3:

在这里插入图片描述

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
/*开始需要判断head是否为NULL,否则下面while循环条件就是报错了
runtime error: member access within null pointer of 
type 'struct ListNode' [solution.c]
另外这里的双指针都指向head,快指针指向head->next,则还需检验
head->next是否为空*/
    if(head == NULL)
        return false;
    struct ListNode *slow = head, *fast = head;
    int ret = 0;

    while(fast->next != NULL && fast->next->next != NULL  ) {/*这里只用检验快指针,因为如果无环,快指针先到达NULL,另外
    要检查下面相邻的两个,如果无环,快指针最后可能指向NULL的前一
    或倒数第二个,如果只检查一个的话会报错runtime error: 
    member access within null pointer of type 
    'struct ListNode' [solution.c]*/
        slow = slow->next;
        fast = fast->next->next;
        if(slow == fast){
            ret = 1;
            break;
        }
    }
    if(ret == 1)
        return true;
    return false;
}

开始做这个题一直在while循环那里报错,总以为自己没问题,没想到啊!!!最后看到错误案例是无环时,于是分析了接近NULL的情况,总算分析出来了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值