LeetCode 环形链表之null pointer错误

该博客主要讨论LeetCode中关于环形链表问题的一个常见错误——空指针异常。作者指出,由于在循环判断过程中未充分考虑指针可能为null的情况,导致编译器报错。解决方案是在循环条件中增加对空指针的检查,确保代码的健壮性。最终,作者提供了修正后的AC(Accepted)代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目大意:
给定一个链表,判断链表中是否有环。

报错代码:

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == NULL){
            return false;
        }
        ListNode* tmp1 = head;
        ListNode* tmp2 = head;
        while(tmp1->next != NULL && tmp2->next->next != NULL){
            tmp1 = tmp1 -> next ;
            tmp2 = tmp2 -> next -> next;
            if(tmp1->val == tmp2 -> val){
                return true;
            }
        }
        return false;
    }
};

错误信息:

Line 17: member access within null pointer of type 'struct ListNode'

原因:

我们在while循环中判断了tmp1->nexttmp2->next->next这两个指针是否为空,但是在判断tmp1->next的时候,编译器不知道tmp1是否为空,在判断tmp2->next->next的时候,编译器不知道tmp2->nexttmp2是否为空,因为编译器无法确定,所以报错。

解决方法:

while循环中将编译器不知道的指针也进行判断,也就是说,将条件写全一点就OK了。

AC代码:

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == NULL){
            return false;
        }
        ListNode* tmp1 = head;
        ListNode* tmp2 = head;
        while(tmp1 != NULL && tmp2 != NULL && tmp1->next != NULL && tmp2->next != NULL && tmp2->next->next != NULL){
            tmp1 = tmp1 -> next ;
            tmp2 = tmp2 -> next -> next;
            if(tmp1->val == tmp2 -> val){
                return true;
            }
        }
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值